Java文件复制

介绍三种复制文件的方法:
1. 流。
这种模式就是将文件读如到(输入)流,写入到byte数组,然后将byte数组写入到输出流。

/*将test.txt的内容复制到copy.txt*/
File file = new File("test.txt");
InputStream inputStream = new FileInputStream(file);
OutputStream outputStream = new FileOutputStream("copy.txt");
byte[] b = new byte[1024];
int read = 0;
while((read = inputStream.read(b))>0)
{
outputStream.write(b, 0, read);
}
inputStream.close();
outputStream.close();

2. java1.4以后的Channel和Buffer。通过这种方式读写文件与流差不多。输入流输出流通过getChannel得到对应的Channel对象,Channel操作的是Buffer。Buffer类似于数组,但是他有个好处就是Buffer对象拥有两个方法:filp和clear方法。filp会将Buffer中没有数据的存储空间“封印”起来,避免Buffer读到null,为取出数据做准备,clear将指针置为0,为装入数据做好准备。

/*将test.txt复制到copy.txt*/
File file = new File("test.txt");
@SuppressWarnings("resource")
FileChannel inchannel = new FileInputStream(file).getChannel();
@SuppressWarnings("resource")
FileChannel outchannel = new FileOutputStream("copy.txt").getChannel();
ByteBuffer byteBuffer = inchannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
outchannel.write(byteBuffer);
inchannel.close();
outchannel.close();


3. Files工具类。Path是java7之后File的取代品。“File类功能有限,方法效率不高,大多数情况下不能返回异常信息。”

/*Paths.get()方法得到对应的Path对象(运行此段代码,您的jdk版本必须高于等于7)*/
Files.copy(Paths.get("test.txt"), new FileOutputStream("copy.txt"));


- 总结:第一种方法比较繁琐,你需要创建输入流输出流,存放数据的数组,最后还有记得关闭流(如果使用try{}catch{}则不必)他相较于第二种方法来说,效率不高(每次处理一个字节),不能异步(阻塞式读取)。
- 第二种方法的优势在于,Channel有一个map()方法可以直接将一块数据映射到内存中,效率提高很多,但是如果一次读入内存的文件过大会引起性能下降。不过Buffer也是支持一次次向Channel取数据的。
- 第三种方法是最快捷的,他只需要一行代码即可,至于效率问题我没做研究。值得一提的是,对于第三种方法,如果test.txt不存在,程序会提示NoSuchFileException异常,但是仍会创建copy.txt,只是这个copy.txt的大小为0。最后,第三种方法不能用于文件夹的复制(即使Path可以是一个路径)。

原文地址:https://www.cnblogs.com/MasterE/p/6670915.html