1. 程式人生 > >Java NIO 實現文件復制

Java NIO 實現文件復制

print utc code generate pri 循環 while clear generated

/* *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 實現文件復制