首页 > 编程语言 > 详细

java基础:IO流之FileInputStream和FileOutputStream

时间:2021-04-22 16:14:36      阅读:27      评论:0      收藏:0      [点我收藏+]

接着上一篇博客: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();
}

测试结果:

技术分享图片

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

技术分享图片

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

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

技术分享图片

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

关于文件的读取:

  • 对于文本文件(.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可以复制:

技术分享图片

复制文件

对于文件的读取,不建议使用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();
}

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

技术分享图片

java基础:IO流之FileInputStream和FileOutputStream

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!