Java逐行写入字符串到文件

下边是写东西到一个文件中的Java代码。运行后每一次,一个新的文件被创建,并且之前一个也将会被新的文件替代。这和给文件追加内容是不同的。

1    BufferedWriter

  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     }  
 这个例子使用的是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         }  
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针对写字符文件是一个很方便的类。这个类的构造方法假设默认的字符编码和默认的字节缓冲区都是可以接受的。如果要指定编码和字节缓冲区的长度,需要构造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打印格式化对象的表示到一个文本输出流。这个类实现了所有在PrintStream中的打印方法。它不包含用于写入原始字节,因为一个程序应该使用未编码的字节流。

主要区别在于,PrintWriter提供了一些额外的方法来格式化,例如println和printf。此外,万一遇到任何的I/O故障FileWriter会抛出IOException。PrintWriter的方法不抛出IOException异常,而是他们设一个布尔标志值,可以用这个值来检测是否出错(checkError())。PrintWriter在数据的每个字节被写入后自动调用flush 。而FileWriter,调用者必须采取手动调用flush.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值