原文引用https://www.dazhuanlan.com/2019/08/25/5d622ab9a21fa/
这篇文章总结了使用相关类写文档的操作
1. FileOutputStream
12345678910 |
public static void writeFile1() throws IOException { File fout = new File("out.txt"); FileOutputStream fos = new FileOutputStream(fout); BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fos)); for(int i = 0; i < 10; i++) { br.write("test"); br.newLine(); } br.close();} |
这个例子中用了FileOutputStream,你可以使用FileWriter或者PrintWriter代替处理txt格式的文档操作
2. FileWriter
1234567 |
public static void () throws IOException { FileWriter fw = new FileWriter("out.txt"); for(int i = 0; i < 10; i++) { fw.write("something"); } fw.close();} |
3. PrintWriter
12345678 |
public static void writeFile3() throws IOException { PrintWriter pw = new PrintWriter(new FileWriter("out.txt")); for(int i = 0; i < 10; i++) { pw.write("something"); } pw.close(); } |
4. OutputStreamWriter
123456789 |
public static void writeFile4() throws IOException { File fout = new File("out.txt"); FileOutputStream fos = new FileOutputStream(fout); OutputStreamWriter osw = new OutputStreamWriter(fos); for(int i = 0; i < 10; i++) { osw.write("something"); } osw.close();} |
5. 它们的区别
来自Java Doc
主要的区别是,PrintWriter提供格式如println和printf一些额外的方法。此外,FileWriter会抛出异常以防任何一种I/O失败。
PrintWriter方法不抛出IOException,它们设置一个可使用checkerror()获得的boolean型flag位。PrintWriter在每个被写入的数据字节后自动调用flush。涉及到FileWriter,调用者需要注意使用flush。
原文地址:https://www.cnblogs.com/petewell/p/11408044.html
时间: 2024-10-11 21:01:22