IO About file copy

本文介绍如何使用Java的FileInputStream和FileOutputStream进行文件复制,并通过缓存优化提高效率。详细展示了复制过程中的关键步骤及如何利用缓存减少IO操作。

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

package demo;

import java.io.*;

public class TestCopy{
public void testCopy()throws Exception{
FileInputStream fis = new FileInputStream("c:/爱是永恒.mp3");
int offset = 0;
FileOutputStream fos = new FileOutputStream("d:/test.mp3");
while((offset = fis.read()) != -1){
fos.write(offset);
}
fis.close();
fos.close();
}

//使用缓存来提高效率
public void testCopy2()throws Exception{
FileInputStream fis = new FileInputStream("c:/爱是永恒.mp3");
//定义一个缓存用来装载读取到的文件
byte[] temp = new byte[1024];
int offset = 0;
FileOutputStream fos = new FileOutputStream("d:/test2.mp3");
//fis.read(temp) 把文件内容读取到temp数组,读到temp满为止或者没有内容
//fis.read(temp)的返回值是实际读取进数组的字节个数
while((offset = fis.read(temp)) != -1){
//每次把一整个数组的数据写入文件,0表示从temp的第0个位置开始读取,
//一共读取offset个写入到内容
fos.write(temp,0,offset);
}
fis.close();
fos.close();
}

public static void main(String[] args)throws Exception{
TestCopy t = new TestCopy();
t.testCopy2();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值