OutputStream 简介

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class OutputStreamDemo {
   /*
    * 子类的后缀和父类相同,FileOutputStream是OutputStream的子类。
    * OutputStream:字节输出流
    * FileOutputStream:文件字节输出流。以字节为单位进行数据传输,
    *   传输至文件中。
    * ---->构造方法
    * 1.new FileOutputStream(File file):
    *    传入File对象,作为目标文件。通过字节流把内容写入文件中。
    * 2.new FileOutputStream(File file, boolean append)
    *    传入File对象,作为目标文件。通过字节流把内容写入文件中。
    *    boolean append 代表是否续写。
    *    如果为true则续写,如果为false则覆盖(不续写)。
    *    
    * 3.new FileOutputStream(String name)
    *   传入一个String的文件路径,该路径代表的文件作为目标文件。
    *   如果该路径表示的文件的父级路径存在,而文件不存在则直接创建文件。
    *   如果该路径表示的文件的父级路径不存在,会抛FileNotFoundException异常。
    *   
    * 4.  new FileOutputStream(String name,boolean append)
    *    传入一个String的文件路径,该路径代表的文件作为目标文件。
    *    如果该路径表示的文件的父级路径存在,而文件不存在则直接创建文件。
    *    如果该路径表示的文件的父级路径不存在,会抛FileNotFoundException异常。
    *    boolean append 代表是否续写。
    *    如果为true则续写,如果为false则覆盖(不续写)。
    *   
    */
   public static void main(String[] args) {
      //1.创建文件对象
      File file = new File("D:/demo/test/a.txt");
      //2.获得父级路径File对象
      File parent = file.getParentFile();
      //3.如果父级路径不存在,则创建
      if(!parent.exists()){
         parent.mkdirs();
      }
      //4.如果文件不存在,则创建
      if(!file.exists()){
         try {
            file.createNewFile();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
      //创建输出流,封装了目标文件。
      OutputStream os = null;
      try {
         os = new FileOutputStream(file);
         /*
          * 1.write(int b):一次写入一个字节
          */
         /*String str = "abcdefg";
         byte[] bytes = str.getBytes();
         for (int i = 0; i < bytes.length; i++) {
            os.write(bytes[i]);
         }
         */
         /*
          * 2.write(byte[] b):把参数数组中的内容写入文件
          */
      /* byte[] bytes = "abcdefg".getBytes();
         os.write(bytes);*/
         /*
          * 3.
          *  write(b, off, len);
          *  传入一个byte类型数组,把数组中从下标为off开始len个字节
          *  写入文件
          */
         byte[] bytes = "abcdefg".getBytes();
         os.write(bytes, 0, bytes.length);
        
      } catch (IOException e) {
         e.printStackTrace();
      }finally{
         if(os != null){
            try {
               os.close();//关闭资源
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
   }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值