import java.io.*;
public class CopyFile{
//文件通过节点流复制功能封装为方法
public void copyFile(String srcPath,String destPath){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//1.创建File类对象
File srcFile = new File(srcPath);
File destFile = new File(destPath);
//2.创建输入流和输出流对象
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
//3.数据的读入和写出操作
byte[] bytes = new byte[1024];
int len;
while((len = fis.read(bytes)) != -1){
fos.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.关闭流资源
try {
if(fis != null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fos != null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// //文件通过缓冲流复制功能封装为方法
public void copyFileWithBuffered(String srcPath,String destPath){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.创建File类对象
File srcFile = new File(srcPath);
File destFile = new File(destPath);
//2.2.创建输入流和输出流对象
//2.1创建节点流对象
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
//2.2创建缓冲流对象
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.复制的细节:读取、写入
byte[] buffer = new byte[1024];
int len;
while((len = bis.read(buffer)) != -1){
bos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.关闭资源
//要求:先关闭外层的流,再关闭内层的流
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//说明:关闭外层流的同时,内层流也会关闭
// fos.close();
// fis.close();
}
}
}
class TestCopyFile{
public static void main(String[] args){
CopyFile copyFile = new CopyFile();
long start = System.currentTimeMillis();
String srcPath = "J:\\01.rar";
String destPath = "C:\\Users\\qqq\\Desktop\\01.rar";
copyFile.copyFile(srcPath,destPath);
long end = System.currentTimeMillis();
System.out.println("复制文件成功,耗时为:" + (end - start) + "毫秒");
System.out.println("---------------此处为分割线---------------");
long start1 = System.currentTimeMillis();
String srcPath = "J:\\01.rar";
String destPath = "C:\\Users\\qqq\\Desktop\\01.rar";
copyFile.copyFileWithBuffered(srcPath,destPath);
long end1 = System.currentTimeMillis();
System.out.println("复制文件成功,耗时为:" + (end1 - start1) + "毫秒");
}
}
结论:使用缓冲流BufferedInputStream、BufferedOutputStream后效率明显提升。
本文探讨了两种Java代码文件复制方法,分别使用节点流和缓冲流进行文件复制。通过实验,结论指出利用缓冲流BufferedInputStream和BufferedOutputStream进行文件复制的效率显著提高。
489

被折叠的 条评论
为什么被折叠?



