282 字节流写数据的2个小问题

36 篇文章 0 订阅

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 }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值