java学习---OutputStream

FileOutputStream

1、 简介

官话:用于将数据写入FileFileDescriptor的输出流。

  • 文件是否可用或是否可以创建取决于底层平台。特别是某些平台允许一次仅打开一个文件以供写入FileOutputStream (或其他文件写入对象)。在这种情况下,如果涉及的文件已经打开,则此类中的构造函数将失败。

  • FileOutputStream用于写入诸如图像数据的原始字节流,因此也叫字节输出流。

  • 要释放此流使用的资源,应 直接通过 try-with-resources调用close()方法进行流的关闭,而且在流用完之后应立即进行关闭,因为流的存在很占用资源而且GC不能自动的进行回收。

2、 方法解释

 2.1 方法描述

  • 构造方法

传入StringFile类型的参数的用法都是一样的,只记录File时的情况即可。

如果传入的文件对象有效,即使不存在也会自动创建该文件。

FileOutputStream(String name)FileOutputStream(String name, boolean append) 两个方法和传入File对象时的用法一致,只是后者传入的是抽象路径名,前者是一个字符串形式。

构造器描述
FileOutputStream(File file)创建文件输出流以写入由参数指定的 File对象表示的文件。
FileOutputStream(File file, boolean append)创建文件输出流以追加的形式写入文件。
FileOutputStream(String name)创建文件输出流以写入具有指定名称的文件。
FileOutputStream(String name, boolean append)创建文件输出流以追加的形式写入具有指定名称的文件。
FileOutputStream(FileDescriptor fdObj)创建要写入指定文件描述符的文件输出流,该文件描述符表示与文件系统中实际文件的现有连接。
  • 常用方法
变量和类型方法描述
voidwrite(int b)将指定的字节写入此文件输出流。
voidwrite(byte[] b)将指定字节数组中的 b.length字节写入此文件输出流。
voidwrite(byte[] b, int off, int len)将从偏移量 off开始的指定字节数组中的 len个字节写入此文件输出流。
voidclose()关闭此文件输出流并释放与此流关联的所有系统资源。
  • 其他方法

 2.2 方法解释

  2.2.1 FileOutputStream(File file)

  创建文件输出流 以写入由参数指定的 File 对象表示的文件。

  • 首先,如果有安全管理器,则调用其checkWrite方法,并将file参数表示的路径作为其参数。

  • 如果文件存在但是是目录而不是常规文件、不存在但无法创建,或者由于任何其他原因无法打开,则抛出FileNotFoundException 异常 。

  • 内部源码

    public FileOutputStream(File file) throws FileNotFoundException {
        // 实际调用的是追加写入的构造器
            this(file, false);
        }
    
  • 代码测试

    public static void main(String[] args) {
            try (FileOutputStream out = new FileOutputStream(new File("1.txt"))) {
                System.out.println(out.toString());
                // java.io.FileOutputStream@129a8472
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    
  2.2.2 FileOutputStream(File file, boolean append)

  和FileOutputStream(File file)一个用法,只是第二个参数boolean可以指定是否以追加的形式写入文件。

  • 如果为true的话将在文件的末尾进行写入数据。

  • 如果为false的话将在文件的开头重新写入文件。

  • 内部源码

    public FileOutputStream(File file, boolean append) throws FileNotFoundException {
            this.closeLock = new Object();
        // 判断路径是否为空 
            String name = file != null ? file.getPath() : null;
        // 拿到安全管理器的对象
            SecurityManager security = System.getSecurityManager();
            if (security != null) {
                // 判断文件是否可写
                security.checkWrite(name);
            }
            if (name == null) {
                // 路径为null抛出空指针异常
                throw new NullPointerException();
            } else if (file.isInvalid()) {
                throw new FileNotFoundException("Invalid file path");
            } else {
                this.fd = new FileDescriptor();
                this.fd.attach(this);
                this.path = name;
                this.open(name, append);
                this.altFinalizer = getFinalizer(this);
                if (this.altFinalizer == null) {
                    FileCleanable.register(this.fd);
                }
            }
        }
    
  • 代码测试

    public static void main(String[] args) {
            try (FileOutputStream out = new FileOutputStream(new File("1.txt"), true)) {
                System.out.println(out.toString()); 
                // java.io.FileOutputStream@129a8472
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    
  2.2.3 FileOutputStream(String name)

  创建文件输出流以写入具有指定名称的文件。

  • 如果文件存在但是是目录而不是常规文件,则不存在但无法创建,或者由于任何其他原因无法打开,则抛出FileNotFoundException

  • 内部源码

    public FileOutputStream(String name) throws FileNotFoundException {
            this(name != null ? new File(name) : null, false);
        }
    
  • 代码测试

    public static void main(String[] args) throws FileNotFoundException {
            FileOutputStream outputStream = new FileOutputStream("2.txt");
            try {
                // 以覆盖的形式向文件中写入一个字符‘1’
                outputStream.write('1');    
                // 关闭文件流
                outputStream.close();       
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
  2.2.4 FileOutputStream(String name, boolean append)

  创建文件输出流以写入具有指定名称的文件。 如果第二个参数是true ,则字节将写入文件的末尾而不是开头

  • 如果文件存在但是是目录而不是常规文件,不存在但无法创建,或者由于任何其他原因无法打开,则抛出FileNotFoundException

  • 内部源码

    public FileOutputStream(String name, boolean append) throws FileNotFoundException {
            this(name != null ? new File(name) : null, append);
        }
    
  • 代码测试

    public static void main(String[] args) throws FileNotFoundException {
            FileOutputStream outputStream = new FileOutputStream("2.txt", true);
            try {
                // 以追加的形式向文件中写入一个字符‘1’
                outputStream.write('1');
                // 关闭文件流
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
  2.2.5 write(int b)

  将指定的字节写入此文件输出流。

  • 内部源码

    public void write(int b) throws IOException {
            this.write(b, fdAccess.getAppend(this.fd));
        }
    
  • 代码测试

    public static void main(String[] args) throws FileNotFoundException {
            // 以覆写的形式创建一个文件输出流
            FileOutputStream out = new FileOutputStream(new File("2.txt"));
            try {
                // 向流中写入数据,会转换成相应的字符
                out.write(52);    // 存储在文件中的数据是 4
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    // 关闭文件流
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
  2.2.6 write(byte[] b)

  将指定字节数组中的 b.length个字节写入此文件输出流。

  • 内部源码

    public void write(byte[] b) throws IOException {
            this.writeBytes(b, 0, b.length, fdAccess.getAppend(this.fd));
        }
    
  • 代码测试

    public static void main(String[] args) throws FileNotFoundException {
            // 以覆写的形式创建一个文件输出流
            FileOutputStream out = new FileOutputStream(new File("2.txt"));
            try {
                // 向流中写入字节数组 [85,86,87,88]
                out.write(new byte[]{85,86,87,88});
                // 存储到文件数据为 UVWX
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    // 关闭文件流
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
  2.2.7 write(byte[] b)

  将从偏移量为off的指定字节数组中的len字节写入此文件输出流。

  • 内部源码

    public void write(byte[] b, int off, int len) throws IOException {
            this.writeBytes(b, off, len, fdAccess.getAppend(this.fd));
        }
    
  • 代码测试

    public static void main(String[] args) throws FileNotFoundException {
            // 以覆写的形式创建一个文件输出流
            FileOutputStream out = new FileOutputStream(new File("2.txt"));
            try {
                // 向流中写入字节数组 [85,86,87,88] 从索引1开始的2个字节
                out.write(new byte[]{85,86,87,88}, 1, 2);
                // 存储到文件数据为 VW
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    // 关闭文件流
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
  2.2.8 close()

  关闭此文件输出流并释放与此流关联的所有系统资源。 此文件输出流可能不再用于写入字节。

  • 仅当直接调用或通过try-with-resources调用时,重写close()才能执行清理操作。 不要依赖于最终化来调用close ; 最终确定不可靠并且已被弃用。 如果需要清理本机资源,则应使用其他机制,如Cleaner

  • 内部源码

    public void close() throws IOException {
            if (!this.closed) {
                synchronized(this.closeLock) {
                    if (this.closed) {
                        return;
                    }
    
                    this.closed = true;
                }
                FileChannel fc = this.channel;
                if (fc != null) {
                    fc.close();
                }
                this.fd.closeAll(new Closeable() {
                    public void close() throws IOException {
                        FileOutputStream.this.fd.close();
                    }
                });
            }
        }
    
  • 代码测试

    public static void main(String[] args) throws FileNotFoundException {
            // 以覆写的形式创建一个文件输出流
            FileOutputStream out = new FileOutputStream(new File("2.txt"));
            try {
                // 关闭当前输出流
                out.close();
                // 使用流文件写入数据
                out.write(1);    // 发生异常 java.io.IOException: Stream Closed
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
      FileOutputStream out = new FileOutputStream(new File("2.txt"));
        try {
            // 关闭当前输出流
            out.close();
            // 使用流文件写入数据
            out.write(1);    // 发生异常 java.io.IOException: Stream Closed
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    
    
    
    
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值