使用Channel进行本地文件读写的简单实例2
Posted mc-74120
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Channel进行本地文件读写的简单实例2相关的知识,希望对你有一定的参考价值。
使用一个缓冲区进行读写操作:
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("1.txt");
FileChannel channel01 = fileInputStream.getChannel();
FileOutputStream fileOutputStream=new FileOutputStream("2.txt");
FileChannel channel02 = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//循环读取
while(true){
//清理缓冲区 非常重要
byteBuffer.clear();
int read= channel01.read(byteBuffer);
if(read==-1){
break;
}
byteBuffer.flip();
channel02.write(byteBuffer);
}
fileInputStream.close();
fileOutputStream.close();
}
直接通过channel进行读写
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("d:\eva.jpg");
FileOutputStream fileOutputStream = new FileOutputStream("d:\eva2.jpg");
FileChannel channel01 = fileInputStream.getChannel();
FileChannel channel02 = fileOutputStream.getChannel();
channel02.transferFrom(channel01,0,channel01.size());
channel01.close();
channel02.close();
fileInputStream.close();
fileOutputStream.close();
}
以上是关于使用Channel进行本地文件读写的简单实例2的主要内容,如果未能解决你的问题,请参考以下文章