InputSream的read和OutputStream的write

本文详细介绍了如何使用Java进行文件复制,包括使用InputStream和OutputStream进行文件读写的具体步骤,并解释了读写过程中涉及的关键概念。

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

先从这一段代码开始:

private void copyFile(String srcPath, String destPath) throws IOException {
        // 源文件
        File srcFile = new File(srcPath);
        // 输出文件
        File destFile = new File(destPath);
        // 输入流-将源文件读取到内存
        InputStream in = new FileInputStream(srcFile);
        // 输出流-从内存中读取并写到磁盘
        OutputStream out = new FileOutputStream(destFile);
        // 容器
        byte[] flush = new byte[1024];
        // 长度
        int length;
        int count=0;
        //一次最多读取1024个,同时一次也写入最多1024;边读边写
        while ((length = in.read(flush)) != -1) {
            System.out.println("length:" + length);
            out.write(flush, 0, length);
            ++count;
        }
        System.out.println(count);
        // 关闭流
        in.close();
        out.close();
    }

打印的结果:

length:1024

...

length:1024
length:173
196

一共打印了196次,所以这个文件的总长度为:1024*195+173

当你遇到IO的时候,就想两件事,第一,我的内存是中心,第二看看流的方向(矢量)!

读文件
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(“infilename”)));
不管你从磁盘读,从网络读,或者从键盘读,读到内存,就是InputStream。

写文件
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(“outfilename”)));
不管你写倒磁盘,写到网络,或者写到屏幕,都是OuputStream。

参考:

InputStream与OutputStream的比较
InputStream类中的三种read方法


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值