1. 使用文件流复制
这是最经典的方式将一个文件的内容复制到另一个文件中。 使用FileInputStream读取文件一个的字节,使用FileOutputStream写入到文件B。
这是第一个方法的代码:
私有静态孔隙copyFileUsingFileStreams(文件来源,文件dest)
抛出IOException {
InputStream输入=零;
OutputStream输出=零;
尝试{
输入=new FileInputStream(源);
输出=new FileOutputStream(桌子);
byte [] buf=新字节[1024];
int bytesRead;
而((bytesRead=input.read (buf))比;0) {
输出。写(buf 0 bytesRead);
}
最后}{
input.close ();
output.close ();
}
}
正如你所看到的我们执行几个读和写操作试的数据,所以这应该是一个低效率的,下一个方法我们将看到新的方式。
2. 使用FileChannel复制
Java NIO包括transferFrom方法,根据文档应该比文件流复制的速度更快。
这是第二种方法的代码:
私有静态孔隙copyFileUsingFileChannels(文件来源,文件dest) 抛出IOException {
FileChannel inputChannel=零;
FileChannel outputChannel=零;
尝试{
inputChannel=new FileInputStream(源).getChannel ();
outputChannel=new FileOutputStream(桌子).getChannel ();
outputChannel。transferFrom (inputChannel 0 inputChannel.size ());
最后}{
inputChannel.close ();
outputChannel.close ();
}
}
<中心> java复制文件的4种方式