code 1:将特定String写入特定文件,不覆盖。
import java.io.*;
import java.util.*; public class OutputLog {
public static void main(String[] args) {
outPutLogToDeaktop("log.txt", "11111111111");
outPutLogToDeaktop("log.txt", "222222");
} public static void outPutLogToDeaktop(String fileName, String info) {
File out_file = new File("/home/wangyong/Desktop/" + fileName);
try {
FileWriter fw = new FileWriter(out_file, out_file.exists());
fw.write( (new Date()).toString() + " : " + info + "\n" );
fw.close();
} catch (IOException e) {
System.out.println("FileWriter IOException!");
e.printStackTrace();
}
}
}
FileWriter fw = new FileWriter(out_file, out_file.exists()); 这一句,如果out_file.exists()为真,则以Append(在文本最后添加而不覆盖)方式写新内容,如果out_file.exists()为假,创建文件并写入。
输出结果:
Fri Jan 03 19:07:52 CST 2014 : 11111111111
Fri Jan 03 19:07:52 CST 2014 : 222222
Fri Jan 03 19:07:53 CST 2014 : 11111111111
Fri Jan 03 19:07:53 CST 2014 : 222222
code 2: 直接将控制台的输出写入文件
import java.io.*;
import java.util.*; public class OutputLog {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("yyyy.txt");
System.setOut(new PrintStream(fos));
System.out.println("frfr");
}
}
code 3: 一行一行读文件
String s;
FileReader fr=new FileReader("public.txt");
BufferedReader br=new BufferedReader(fr);
while((s=br.readLine())!=null)
System.out.println(s);
br.close();