当前位置: 首页 > news >正文

IO流——字节输入输出流:FileInputStream FileOutputStream

一、认识IO流(输入输出流)

I是Input,称为输入流:负责把数据读到内存中去。

O是output,称为输出流:负责把数据写出去

二、IO流的应用场景

三、如何学习IO流

1. 先搞清楚IO流的分类、体系

2. 每个IO流的作用、用法

(1)实现类——FileInputStream 文件字节输入流

作用:以内存为基准,可以把磁盘文件种的数据以字节的形式读入到内存种去。

多用多态的方式写代码

① 文件字节输入流:每次读取一个字节

② 文件字节输入流:每次读取多个字节

③ 文件字节输入流:一次读完全部字节

方式一:自己定义一个字节数组与被读取的文件大小一样大,然后使用该字节数组,一次读完文件的全部字节。

方式二:Java官方为InputStream提供了如下方法,可以直接把文件的全部字节读取到一个字节数组中并返回。

(2)实现类——FileOutputStream 文件字节输出流

④ 文件字节输出流:写字节出去

作用:以内存为基准,把内存中的数据以字节的形式写出到文件中去

public class Test1 {
    public static void main(String[] args) throws Exception {
        //覆盖管道
      // OutputStream os =
              // new FileOutputStream("E:\\1. Java related\\JavaCode\\file-io-stream\\src\\itheimaOutTest01.txt");
      //追加数据管道
        OutputStream os =
                new FileOutputStream("E:\\1. Java related\\JavaCode\\file-io-stream\\src\\itheimaOutTest01.txt",true);
       os.write(97);
        byte[] bytes = "我爱你中国forever".getBytes();
        os.write(bytes);
        os.write(bytes, 0, 15);

        //换行符号
        os.write("\r\n".getBytes());
        os.close();
    }
}
⑤ 文件复制案例

字节流非常适合做一切文件的赋值操作,任何文件的底层都是字节,字节流做复制,是一字不漏的转移完全部字节,只要复制后的格式一致,就没问题


public class Test2 {
    public static void main(String[] args) throws Exception {
        InputStream is = new FileInputStream("E:\\1. Java related\\xiaogou.png");
        OutputStream os = new FileOutputStream("D:\\Personal\\xiaogou.png");

        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer))!= -1){
            os.write(buffer,0,len);
        }
        os.close();
        is.close();
        System.out.println("复制完成");
    }
}
⑥ 释放资源的方式
方式一:try-catch-finally

finally代码区的特点:无论try中的程序时正常执行了,还是出现了异常,最后都一定会执行finally区,除非JVM终止。

作用:一般用于在程序执行完成后进行资源的释放操作

//书写格式
try(){
...
...
}catch(IOException){
    e.printStackTrace();
}finally{

}

错误代码示范注意事项

优化复制文件模块儿的代码

public class Test2 {
    public static void main(String[] args) throws Exception {
        //ctrl+alt+t--选择8号
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream("E:\\3. Studies\\xiaogou.png");
            os = new FileOutputStream("D:\\Personal\\xiaogou.png");

            byte[] buffer = new byte[1024];
            int len;
            while((len = is.read(buffer))!= -1){
                os.write(buffer,0,len);
            }
            System.out.println("复制完成");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //释放资源的专业操作
            try {
                if (os != null )os.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                if(is != null )is.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
方式二:try-with-resource

该资源使用完毕后,会自动调用其close()方法,完成对资源的释放

//try-with-resource格式
try(定义资源1; 定义资源2; ...){
可能出现异常的代码;
}catch(异常类名 变量名){
    异常的处理代码
}

继续优化复制文件模块儿的代码

public class Test3 {
    public static void main(String[] args) throws Exception {
        //ctrl+alt+t--选择8号
        try( InputStream is = new FileInputStream("E:\\3. Studies\\xiaogou.png");
             OutputStream os = new FileOutputStream("D:\\Personal\\xiaogou.png");
             //这里只能放置资源对象(流对象)
             ) {
            byte[] buffer = new byte[1024];
            int len;
            while((len = is.read(buffer))!= -1){
                os.write(buffer,0,len);
            }
            System.out.println("复制完成");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

注意事项

· ()中只能放置资源,否则报错

· 资源一般指的是最终实现了AutoCloseable接口

主要有

//1. 
public abstract class InputStream implements Closeable {}

//2. 
public abstract class OutputStream implements Closeable, Flushable{}

//3. 
public interface Closeable extends AutoCloseable{}

相关文章:

  • 视频内容原数据获取接口开发指南
  • 直线模组过载使用会有什么效果?
  • 数据驱动的温暖守护:智慧康养平台如何实现 “千人千面” 的精准照护?
  • Python 根据多个下标向列表中插入对应的值的巧妙方法:逆序插入
  • React8+taro开发微信小程序,实现lottie动画
  • 编程规范(c++)
  • ecovadis评分要求,如何提高ecovadis分数,未来展望
  • GitHub 趋势日报 (2025年04月10日)
  • STM32嵌入式开发从入门到实战:全面指南与项目实践
  • 《Vue Router实战教程》19.滚动行为
  • 原生多模态大模型时代:统一感知的智能跃迁
  • Vue 3 国际化实战:支持 Element Plus 组件和语言持久化
  • Git开发
  • 【Java集合】TreeSet、TreeMap源码解读
  • BERT - 直接调用transformers.BertModel, BertTokenizerAPI不进行任何微调
  • C++动态分配内存知识点!
  • vue2使用ezuikit-js播放萤石视频
  • 手撕红黑树
  • Python Lambda表达式详解
  • Vue 3 响应式更新问题解析
  • 重新设置wordpress/谷歌网站优化推广
  • 家在深圳房网论坛首页/搜索引擎优化工具
  • 时空网站建设的可行性分析/营销策略有哪些4种
  • 旅游网站建设案例分析/网站域名在哪里查询
  • 深圳专业网站建设制作价格低/去哪里推广软件效果好
  • 金华建设网站/百度账号登录不了