Java笔记 使用字节流复制文件
法一,使用一个字节一个字节复制,效率慢,法二,使用字节数组来进行复制,效率快
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.junit.Test;
public class CopyPractice {
public static void main(String[] args) {
}
@Test
public void testCopy() {
long start1=0,end1=0;//声明两个变量来储存开始复制和完成复制的时间
start1=System.currentTimeMillis();//记录开始复制的时间
copyByByte("Test\\1001.jpg", "Test\\copy01.jpg");//来源目录;目标目录
end1=System.currentTimeMillis();//完成复制的时间
System.out.println(end1-start1);//一个字节法复制所用时间
long start2=0,end2=0;
start2=System.currentTimeMillis();
copyByByteArray("Test\\1001.jpg", "Test\\copy02.jpg");
end2=System.currentTimeMillis();
System.out.println(end2-start2);//字节数组法复制所用时间
}
public static void copyByByte(String sourceName,String targetName) {
FileInputStream input = null;
FileOutputStream output = null;
try {
input = new FileInputStream(sourceName);
output = new FileOutputStream(targetName);
int data ;
while( (data = input.read())!=-1 ) {
output.write(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(input!=null)//判断文件是否为空
input.close();//关闭输入流
} catch (IOException e) {
e.printStackTrace();
}
try {
if(output!=null)
output.close();//关闭输出流,两个流要放在不同的try语句中,防止两个都运行不了
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void copyByByteArray(String sourceName,String targetName) {
FileInputStream input = null;
FileOutputStream output = null;
try {
input = new FileInputStream(sourceName);
output = new FileOutputStream(targetName);
byte[] data = new byte[1024];
int length ;
while( (length = input.read(data))!=-1 ) {
output.write(data,0,length);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(input!=null)
input.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(output!=null)
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
copyByByteArray使用字节数组来进行复制,效率快,copyByByte使用一个字节一个字节复制,效率慢
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通