background image

20 个 Java 程序代码片段

下面是

20 个非常有用的 Java 程序片段,希望能对你有用。

1. 字符串有整型的相互转换

1

String a = String.valueOf(2);   //integer to numeric string   

2

int i = Integer.parseInt(a); //numeric string to an int  

2. 向文件末尾添加内容

3

BufferedWriter out = null;   

4

try {   

5

    out = new BufferedWriter(new FileWriter(”filename”, true));   

6

    out.write(”aString”);   

7

catch (IOException e) {   

8

    // error processing code   

9

finally {   

10

    if (out != null) {   

11

        out.close();   

12

    }   

13

}  

3. 得到当前方法的名字

14

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

4. 转字符串到日期

15

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