FileChannel所实现的是管间通信,与普通的读写不同在进行大文件的读写上有很大的优势;
首先是管道的建立,可以通过I/O流来建立FileChannel;下面是利用通道进行文件复制
public static boolean copy(File start,File end) {
try(
FileInputStream in = new FileInputStream(start);
FileOutputStream out = new FileOutputStream(end);
FileChannel fIn = in.getChannel();
FileChannel fOut = out.getChannel();
){
fIn.transferTo(0, fIn.size(),fOut);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
如果要利用FileChannel进行读写,就需要用ByteBuffer类建立一个缓存区,可以通过Charset来指定字节码,然后对缓存区进行解码
public static String read(FileChannel fileChannel, Charset charset) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(1024);
StringBuilder stringBuilder = new StringBuilder();
fileChannel.read(charset.encode("UTE-8