IO流_FileOutputStream写出数据实现换行和追加写入

来源:互联网 发布:淘宝涮单怎么样更赚钱 编辑:程序博客网 时间:2024/05/16 01:43
  1. package cn.itcast_01;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5.   
  6. /* 
  7.  * 如何实现数据的换行? 
  8.  *      为什么现在没换行呢?因为你只写了字节数据,并没有写入换行符号。 
  9.  *      如保实现呢?写入换行符号即可呗。 
  10.  *      看到有些文本文件是可以的,通过windows自带的那个不行,为什么呢? 
  11.  *      因为不同的系统针对不同的换行实别是不一样的? 
  12.  *      windows:\r\n 
  13.  *      linux:\n 
  14.  *      Mac:\r 
  15.  *      而一些常见的高级记事本,是可以实别任意换行符的。 
  16.  *  
  17.  * 如何实现数据的追加写入? 
  18.  *      用构造方法带第二个参数是true的情况即可 
  19.  */  
  20. public class FileOutputStreamDemo3 {  
  21.     public static void main(String[] args) throws IOException {  
  22.         // 创建输出流对象  
  23.         // FileOutputStream fos = new FileOutputStream("fos3.txt");  
  24.         // 创建一个向具有指定 name 的文件中写入数据的输出文件流。如果第二个参数为 true,则将字节写入文件末尾处,而不是写入文件开始处。  
  25.         FileOutputStream fos = new FileOutputStream("fos3.txt"true);  
  26.   
  27.         // 写出数据  
  28.         for (int x = 0; x < 10; x++) {  
  29.             fos.write(("helloworld" + x).getBytes());  
  30.             // fos.write("\r".getBytes());  
  31.             fos.write("\r\n".getBytes());  
  32.         }  
  33.   
  34.         // 关闭输出流  
  35.         // 关闭输出流,让输出流成为垃圾,让系统回收  
  36.         // 通知系统释放该文件相关的资源  
  37.         fos.close();  
  38.     }