20個Java程序片段(1-5)

1. 字符串有整型的相互轉換

1
2
3
String a = String.valueOf(2);   //integer to numeric string  
inti = Integer.parseInt(a); //numeric string to an int


2. 向文件末尾添加內容

1
2
3
4
5
6
7
8
9
10
11
12
BufferedWriter out = null;  
try{  
out = newBufferedWriter(newFileWriter(”filename”, true));  
out.write(”aString”);  
} catch(IOException e) {  
// error processing code  
} finally{  
if(out != null) {  
out.close();  
}  
}

3. 得到當前方法的名字

1
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();

4. 轉字符串到日期

1
2
java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);

或者是:

1
2
3
SimpleDateFormat format = newSimpleDateFormat( "dd.MM.yyyy");  
Date date = format.parse( myString );

5. 使用JDBC鏈接Oracle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
publicclassOracleJdbcTest  
{  
String driverClass = "oracle.jdbc.driver.OracleDriver";  
Connection con;  
publicvoidinit(FileInputStream fs) throwsClassNotFoundException, SQLException, FileNotFoundException, IOException  
{  
Properties props = newProperties();  
props.load(fs);  
String url = props.getProperty("db.url");  
String userName = props.getProperty("db.user");  
String password = props.getProperty("db.password");  
Class.forName(driverClass);  
con=DriverManager.getConnection(url, userName, password);  
}  
publicvoidfetch() throwsSQLException, IOException  
{  
PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");  
ResultSet rs = ps.executeQuery();  
while(rs.next())  
{  
// do the thing you do  
}  
rs.close();  
ps.close();  
}  
publicstaticvoidmain(String[] args)  
{  
OracleJdbcTest test = newOracleJdbcTest();  
test.init();  
test.fetch();  
}  
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章