Java逐行写入字符串到文件
下邊是寫東西到一個文件中的Java代碼。運行后每一次,一個新的文件被創(chuàng)建,并且之前一個也將會被新的文件替代。這和給文件追加內(nèi)容是不同的。
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,如果是針對文本文件的操作是完全綽綽有余的。
2、使用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文檔:
FileWriter is a convenience class for writing character files.The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable.To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
FileWriter針對寫字符文件是一個很方便的類。這個類的構(gòu)造方法假設(shè)默認(rèn)的字符編碼和默認(rèn)的字節(jié)緩沖區(qū)都是可以接受的。如果要指定編碼和字節(jié)緩沖區(qū)的長度,需要構(gòu)造OutputStreamWriter。
PrintWriter
prints formatted representations of objects to a text-output stream.This class implements all of the print methods found in PrintStream.It
does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
PrintWriter打印格式化對象的表示到一個文本輸出流。這個類實現(xiàn)了所有在PrintStream中的打印方法。它不包含用于寫入原始字節(jié),因為一個程序應(yīng)該使用未編碼的字節(jié)流。
主要區(qū)別在于,PrintWriter提供了一些額外的方法來格式化,例如println和printf。此外,萬一遇到任何的I/O故障FileWriter會拋出IOException。PrintWriter的方法不拋出IOException異常,而是他們設(shè)一個布爾標(biāo)志值,可以用這個值來檢測是否出錯(checkError())。PrintWriter在數(shù)據(jù)的每個字節(jié)被寫入后自動調(diào)用flush
。而FileWriter,調(diào)用者必須采取手動調(diào)用flush.
總結(jié)
以上是生活随笔為你收集整理的Java逐行写入字符串到文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Uncaught RangeError:
- 下一篇: vue2.0中watch用法