码迷,mamicode.com
首页 > 编程语言 > 详细

Java中按行写文档的方法

时间:2019-08-25 16:25:27      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:highlight   ble   public   line   ams   href   params   格式   extern   

原文引用https://www.dazhuanlan.com/2019/08/25/5d622ab9a21fa/


这篇文章总结了使用相关类写文档的操作

1. FileOutputStream

1
2
3
4
5
6
7
8
9
10
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

1
2
3
4
5
6
7
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

1
2
3
4
5
6
7
8
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

1
2
3
4
5
6
7
8
9
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。

原文链接

Java中按行写文档的方法

标签:highlight   ble   public   line   ams   href   params   格式   extern   

原文地址:https://www.cnblogs.com/petewell/p/11408044.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!