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

原文地址:https://www.cnblogs.com/wwjj4811/p/14688605.html