• java基础:IO流之FileInputStream和FileOutputStream


    接着上一篇博客:https://www.cnblogs.com/wwjj4811/p/14688283.html

    FileInputStream

    与FileReader读取文件类似,这里不再介绍

    File file = new File("hello.txt");
    try(FileInputStream fis = new FileInputStream(file)){
        byte[] buffer = new byte[5];
        int len;
        while ((len = fis.read(buffer)) != -1){
            String str = new String(buffer, 0, len);
            System.out.print(str);
        }
    }catch (IOException e){
        e.printStackTrace();
    }
    

    测试结果:

    image-20210422103601988

    但是如果文本文件中包含中文,就会有问题:

    image-20210422103643845

    这是因为我们用5个长度字节数组去读取,而一个汉字占三个字节,有可能一个中文字符被分成两次读取而导致乱码。

    如果我们加大字节数组长度,改成100,再进行测试:

    image-20210422103849952

    发现就不乱码了,所有字符被读取到字节数组中,但是这是治标不治本的,因为我们不能知道实际工作中的文本文件有多大!!!

    关于文件的读取:

    • 对于文本文件(.txt .java .c .cpp)使用字符流处理
    • 对于非文本文件(图片、视频、word、ppt...)使用字节流处理

    FileOutputStream

    FileOutputStream的api和使用与FileWriter类似,这里不再详细介绍

    下面使用FileOutputStream和FileInputStream完成图片复制

    File src = new File("a.gif");
    File dest = new File("b.gif");
    try(FileInputStream fis = new FileInputStream(src);
        FileOutputStream fos = new FileOutputStream(dest)){
        byte[] buffer = new byte[100];
        int len;
        while ((len = fis.read(buffer)) != -1){
            fos.write(buffer, 0, len);
        }
    }catch (IOException e){
        e.printStackTrace();
    }
    

    b.gif可以复制:

    image-20210422105545148

    复制文件

    对于文件的读取,不建议使用FileInputStream读取文件,但是对于文件的复制,可以使用FileInputStream和FileInputStream结合,这里FileInputStream,不生产字节,只是字节的搬运工。

    File src = new File("hello.txt");
    File dest = new File("hello2.txt");
    try(FileInputStream fis = new FileInputStream(src);
        FileOutputStream fos = new FileOutputStream(dest)){
        byte[] buffer = new byte[100];
        int len;
        while ((len = fis.read(buffer)) != -1){
            fos.write(buffer, 0, len);
        }
    }catch (IOException e){
        e.printStackTrace();
    }
    

    测试结果:发现中文字符不乱码

    image-20210422110258799

  • 相关阅读:
    Git tag
    Docker学习笔记五 仓库
    Docker学习笔记四 Docker容器
    Docker学习笔记二 使用镜像
    Docker学习笔记一 概念、安装、镜像加速
    element-UI 下拉条数多渲染慢
    scroll-view——小程序横向滚动
    Jquery slider范围滑块,为两个滑块设置不同的setp值
    自说自话2
    自说自话1
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/14688605.html
Copyright © 2020-2023  润新知