首页 > 编程语言 > 详细

Java NIO 实现文件复制

时间:2018-09-11 11:59:06      阅读:140      评论:0      收藏:0      [点我收藏+]
/* *int bytesRead=inChannel.read(buf); * 这句话是从文件流中读取一个buf内容,返回读取的大小, * 如果是读取到文件尾部的时候,返回的是-1 * * 注意FileChannel.write()是在while循环中调用的。 * 因为无法保证write()方法一次能向FileChannel写入多少字节, * 因此需要重复调用write()方法, * 直到Buffer中已经没有尚未写入通道的字节。 * */

@Test
public void test1() {
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel inchannel = null;
FileChannel outchannel = null;
try {
fis = new FileInputStream("1.png");
fos = new FileOutputStream("2.png");
inchannel = fis.getChannel();
outchannel = fos.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
while(inchannel.read(buf)!= -1) {
buf.flip();
outchannel.write(buf);
buf.clear();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(outchannel!=null) {
try{
outchannel.close();
}catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(inchannel!=null) {
try {
inchannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis!=null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fos!=null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

Java NIO 实现文件复制

原文:http://blog.51cto.com/11056727/2173581

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!