JAVA 输入输出 缓冲流(三)

本文档介绍了如何根据文件类型选择使用字符流或字节流,强调了文本文件适合字符流,非文本文件适合字节流,并提供了一个使用缓冲流实现图片复制的Java代码示例。在代码中,通过BufferedInputStream和BufferedOutputStream实现了从源文件到目标文件的高效复制,避免了可能出现的乱码问题。

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

1、字符流、字节流的使用

  • 1、对于文本文件(xxx.txt,xxx.java,xxx.c,xxx.cpp)使用字符流
  • 2、对于非文本文件(xxx.jpg,xxx,mp3,xxx.mp4,xxx.doc,xxx.ppt),使用字节流。
  • 3、如果使用错误,可能会出现乱码。

2、实现图片复制的代码

  • 缓冲流可以让读写更快
package test;

import org.junit.Test;

import java.io.*;

/**
 * 实现非文本文件的复制
 */
public class TestBuffered {
    @Test
    public void test(){
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            //1、造文件
            File srcFile = new File("pujing.png");
            File destFile = new File("pujing1.png");

            //2、造流
            //2.1 节点流
            FileInputStream fileInputStream = new FileInputStream(srcFile);
            FileOutputStream fileOutputStream = new FileOutputStream(destFile);

            //2.2缓冲流
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

            //3、复制的细节
            byte[] buffer = new byte[5];
            int len;
            while ((len = bufferedInputStream.read(buffer)) != -1){
                bufferedOutputStream.write(buffer);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4、资源关闭
            //先关闭外层的流,在关闭内层的流,内层可以省略
            if (bufferedInputStream != null) {

                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {

                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值