Java文件複製(包括NIO)
我們首先定義一個拷貝接口:
public interface FileCopyRunner {
void copyFile(File source, File target) throws IOException;
}
最原始的複製方法(不涉及到緩存)
FileCopyRunner noBufferStreamCopy = (source, target) -> {
int r;
InputStream fin = null;
OutputStream fout = null;
try {
fin = new FileInputStream(source);
fout = new FileOutputStream(target);
while ((r = fin.read()) != -1){
fout.write(r);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
close(fin);
close(fout);
}
};
上面是直接從源文件中讀取出來,然後寫入目標文件中。
基於緩存的文件複製方式
FileCopyRunner bufferedStreamCp = (source, target) -> {
InputStream fin;
OutputStream fout;
fin = new BufferedInputStream(new FileInputStream(source));
fout = new BufferedOutputStream(new FileOutputStream(target));
byte[] buffer = new byte[1024];
int r ;
while((r = fin.read(buffer)) != -1){
fout.write(buffer,0,r);
}
close(fin);
close(fout);
};
上面我們定義了一個1024字節的buffer,每次讀取這麼一個大小放入緩存中,然後一次性寫入文件中。
NIO方式複製
FileCopyRunner nioBufferCopy = (source, target) -> {
FileChannel fin;
FileChannel fout;
fin = new FileInputStream(source).getChannel();
fout = new FileOutputStream(target).getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while(fin.read(buffer) != -1){
buffer.flip();
while(buffer.hasRemaining()) fout.write(buffer);
buffer.clear();
}
close(fin);
close(fout);
};
上面的似乎有些複雜,下面是簡化版。
簡化版NIO
FileCopyRunner nioTransferCopy = (source, target) -> {
FileChannel fin = null;
FileChannel fout = null;
fin = new FileInputStream(source).getChannel();
fout = new FileOutputStream(target).getChannel();
long len = 0L;
while (len != fin.size()) {
len += fin.transferTo(0,fin.size(),fout);
}
close(fin);
close(fout);
};
下面是關閉流close函數的一個定義:
public static void close(Closeable closeable) throws IOException {
if(closeable != null) closeable.close();
}