JAVA基础(FileOutputStream)

本文介绍了JAVA中的FileOutputStream类,主要用于向文件中写入原始字节数据。详细讲解了其构造方法,包括如何创建指向文件的输出流以及是否追加写入。此外,还提到了常用的方法和如何实现文件的读写操作,特别是使用自定义小数组进行读写操作的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,FileOutputStream概念

  • FileOutputStream 用于写入诸如图像数据之类的原始字节的流。用于将数据写入 File 或 FileDescriptor 的输出流。

 

2,构造方法

  • FileOutputStream(File file) file文件要是一个文件不是一个文件夹

file - 为了进行写入而打开的文件。

创建一个向指定 File 对象表示的文件中写入数据的文件输出流。创建一个新 FileDescriptor 对象来表示此文件连接。

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

如果该文件存在,但它是一个目录,而不是一个常规文件;或者该文件不存在,但无法创建它;抑或因为其他某些原因而无法打开,则抛出 FileNotFoundException。

  • FileOutputStream(String name,boolean append)

name - 与系统有关的文件名

append - 如果为 true,则将字节写入文件末尾处,而不是写入文件开始处

  • FileOutputStream(File file, boolean append)

file - 为了进行写入而打开的文件。

append - 如果为 true,则将字节写入文件末尾处,而不是写入文件开始处

 

 

3,常用方法

4,实现写入文件

  •  FileOutputStream fos = new FileOutputStream("yyy.txt",true);   第二个传true 则将字节写入文件末尾处,进行追加写入。
    
    public class Demo2_FileOutputStream {
    
        /**
    
         * @param args
    
         * @throws IOException
    
         * FileOutputStream在创建对象的时候是如果没有这个文件会帮我创建出来
    
         * 如果有这个文件就会先将文件清空
    
         */
    
        public static void main(String[] args) throws IOException {
    
            //demo1();
    
            FileOutputStream fos = new FileOutputStream("yyy.txt",true);    //如果想续写就在第二个参数传true
    
            fos.write(97);
    
            fos.write(98);
    
            
    
            fos.close();
    
        }
    
    
    
    
    
        public static void demo1() throws FileNotFoundException, IOException {
    
            FileOutputStream fos = new FileOutputStream("yyy.txt");        //创建字节输出流对象,如果没有就自动创建一个
    
            //fos.write(97);                //虽然写出的是一个int数,但是到文件上的是一个字节,会自动去除前三个8位
    
            //fos.write(98);
    
            //fos.write(99);
    
            fos.write(100);
    
            fos.close();
    
        }
    
    
    
    
    
    }

     

 

5,自定义小数组进行读写操作

  • byte[] arr = new byte[2];   去读,然后去写

  • fos.write(arr,0,len);

public class Demo4_ArrayCopy {

    /**

     * @param args

     * 第三种拷贝

     * 定义小数组

     * @throws IOException

     */

    public static void main(String[] args) throws IOException {

       FileInputStream fis = new FileInputStream("xxx.txt");

        FileOutputStream fos = new FileOutputStream("yyy.txt");

        

        byte[] arr = new byte[2];

        int len;

        while((len = fis.read(arr)) != -1) {

            fos.write(arr,0,len);

        }

         

        fis.close();

        fos.close();

    }

}



 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

兴帅_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值