在Java之中经常有重命名文件和复制文件的需求,重命名文件使用File.remaneTo()。但是java并没有对复制文件提供接口。现在只能猜测一下原因,可能是因为复制文件有多种形式,需要根据不同的情况作出选择,这个自主权交给了程序员。
1.普通的缓冲输入输出流复制文件
public static void copyFile(File source, File destination){
InputStream fis = null;
OutputStream fos = null;
try {
fis = new BufferedInputStream(new FileInputStream(source));
fos = new BufferedOutputStream(new FileOutputStream(destination));
byte[] buf = new byte[1024];
int i;
while((i = fis.read(buf)) != -1){
fos.write(buf, 0 ,i);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try{
fis.close();
fos.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
这种是最为常见的复制文件的方式,一般情况下就用这个就好了。
2.用文件通道(FileChannel)来实现文件复制
public void fileChannelCopy(File s, File t) {
FileInputStream fi = null;
FileOutputStream fo = null;
FileChannel in = null;
FileChannel out = null;
try {
fi = new FileInputStream(s);
fo = new FileOutputStream(t);
in = fi.getChannel();//流和一个文件通道绑定了,使用getChannel获取与该文件绑定的唯一文件通道
out = fo.getChannel();//得到对应的文件通道
in.transferTo(0, in.size(), out);//连接两个通道,并且从in通道读取,然后写入out通道
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fi.close();
in.close();
fo.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
从上面可以看出文件和流绑定,流和文件通道相绑定。
通常FileChannel复制文件的速度比BufferedInputStream/BufferedOutputStream复制文件的速度快了近三分之一。在复制大文件的时候更加体现出FileChannel的速度优势。而且FileChannel是多并发线程安全的。
所以应用场景为:1.大文件,2.并发