Java NIO 实现文件复制

/*
*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();
}
}
}

}

猜你喜欢

转载自blog.51cto.com/11056727/2173581