字节流写数据练习
  zKfdye51x3nh 2023年12月23日 58 0

方法概述

方法名 说明
void write(int b) 将指定的字节写入此文件输出流 一次写一个字节数据
void write(byte[] b) 将 b.length字节从指定的字节数组写入此文件输出流 一次写一个字节数组数据
void write(byte[] b, int off, int len) 将 len字节从指定的字节数组开始,从偏移量off开始写入此文件输出流 一次写一个字节数组的部分数据
public class FileOutputStream02 {
      public static void main(String[] args) throws IOException {
          //FileOutputStream(String name):创建文件输出流以指定的名称写入文件
          FileOutputStream fos = new FileOutputStream("51cto\\fos.txt");
          //new File(name)
  //        FileOutputStream fos = new FileOutputStream(new File("51cto\\fos.txt"));
  
          //FileOutputStream(File file):创建文件输出流以写入由指定的 File对象表示的文件
  //        File file = new File("51cto\\fos.txt");
  //        FileOutputStream fos2 = new FileOutputStream(file);
  //        FileOutputStream fos2 = new FileOutputStream(new File("51cto\\fos.txt"));
  
          //void write(int b):将指定的字节写入此文件输出流
  //        fos.write(97);
  //        fos.write(98);
  //        fos.write(99);
  //        fos.write(100);
  //        fos.write(101);
  
  //        void write(byte[] b):将 b.length字节从指定的字节数组写入此文件输出流
  //        byte[] bys = {97, 98, 99, 100, 101};
          //byte[] getBytes():返回字符串对应的字节数组
          byte[] bys = "abcde".getBytes();
  //        fos.write(bys);
  
          //void write(byte[] b, int off, int len):将 len字节从指定的字节数组开始,从偏移量off开始写入此文件输出流
  //        fos.write(bys,0,bys.length);
          fos.write(bys,1,3);
  
          //释放资源
          fos.close();
      }
  }

注意事项

  • 字节流写数据如何实现换行

    • windows:\r\n
    • linux:\n
    • mac:\r
  • 字节流写数据如何实现追加写入

    • public FileOutputStream(String name,boolean append)
    • 创建文件输出流以指定的名称写入文件。如果第二个参数为true ,则字节将写入文件的末尾而不是开头
public class FileOutputStream03 {
      public static void main(String[] args) throws IOException {
          //创建字节输出流对象
  //        FileOutputStream fos = new FileOutputStream("51cto\\fos.txt");
          FileOutputStream fos = new FileOutputStream("51cto\\fos.txt",true);
  
          //写数据
          for (int i = 0; i < 10; i++) {
              fos.write("hello".getBytes());
              fos.write("\r\n".getBytes());
          }
  
          //释放资源
          fos.close();
      }
  }

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月23日 0

暂无评论

zKfdye51x3nh