282 字节流写数据的2个小问题
【问题1】字节流写数据如何换行?】
加上换行符\r\n
【问题2】字节流写数据如何追加写入?】
创建FileOutputStream对象时用这个构造方法即可实现追加写入:
FileOutputStream(String name, boolean append)
--------------------------------------------------------------
1 package e282;2
3 import java.io.FileNotFoundException;
4 import java.io.FileOutputStream;
5 import java.io.IOException;6
7 public class FileOutputStreamDemo {
8 public static void main(String[] args) throws IOException {
9 FileOutputStream fos1=new FileOutputStream("myIOStream\\e282-1.txt");
10 FileOutputStream fos2=new FileOutputStream("myIOStream\\e282-2.txt");
11 FileOutputStream fos3=new FileOutputStream("myIOStream\\e282-3.txt",true);
12 //fos3:参数加一个true,写入时从末尾开始添加,而不是从头替换原有内容
13
14 for (int i=0;i<10;i++){
15 fos1.write("hello".getBytes());
16 }//写10次hello,文件内新增了hellohellohellohellohellohellohellohellohellohello
17
18 for (int i=0;i<10;i++){
19 fos2.write("hi".getBytes());
20 fos2.write("\r\n".getBytes());
21 }//e282-2.txt新增了10行hi
22 // 不同操作系统识别的换行不同
23 // windows:\r\n
24 // linux:\n
25 // mac:\r
26 // idea:all
27 // 因此字节输出换行需要加上相应的换行符,\r\n最保险
28
29 // FileOutputStream(String name, boolean append)
30 // 如果第二个参数为true,则字节将写入文件的末尾而不是开头。
31 // 据此创建fos3,行号11
32 for (int i=0;i<10;i++){
33 fos3.write("hey3".getBytes());
34 fos3.write("\r\n".getBytes());
35 }//运行效果,每运行一次,e282-3.txt就多10行的hey3
36 }
37 }