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

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章