这和给文件追加内容是不同的。
1、
1 public static void writeFile1() throws IOException { 2 File fout = new File("out.txt"); 3 FileOutputStream fos = new FileOutputStream(fout); 4 5 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); 6 7 for (int i = 0; i < 10; i++) { 8 bw.write("something"); 9 bw.newLine(); 10 } 11 12 bw.close(); 13 } 14
这个例子使用的是FileOutputStream,你也可以使用FileWriter 或PrintWriter,如果是针对文本文件的操作是完全绰绰有余的。
FileWriter:
1 public static void writeFile2() throws IOException { 2 FileWriter fw = new FileWriter("out.txt"); 3 4 for (int i = 0; i < 10; i++) { 5 fw.write("something"); 6 } 7 8 fw.close(); 9 }
3、使用PrintWriter:
1 public static void writeFile3() throws IOException { 2 PrintWriter pw = new PrintWriter(new FileWriter("out.txt")); 3 4 for (int i = 0; i < 10; i++) { 5 pw.write("something"); //这里也可以用 pw.print("something"); 效果一样 6 } 7 8 pw.close(); 9 }
4、使用OutputStreamWriter:
1 public static void writeFile4() throws IOException { 2 File fout = new File("out.txt"); 3 FileOutputStream fos = new FileOutputStream(fout); 4 5 OutputStreamWriter osw = new OutputStreamWriter(fos); 6 7 for (int i = 0; i < 10; i++) { 8 osw.write("something"); 9 } 10 11 osw.close(); 12 }
摘自Java文档:
To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
如果要指定编码和字节缓冲区的长度,需要构造OutputStreamWriter。
PrintWriter prints formatted representations of objects to a text-output stream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
它不包含用于写入原始字节,因为一个程序应该使用未编码的字节流。
PrintWriter在数据的每个字节被写入后自动调用flush 。而FileWriter,调用者必须采取手动调用flush.