Java NIO 拷贝文件
实现方式一:
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("c:/ntldr");
fos = new FileOutputStream("c:/ntldr.bak");
FileChannel fic = fis.getChannel();
FileChannel foc = fos.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = 0;
while (bytesRead >= 0 || buffer.hasRemaining()) {//---------(1)
if (bytesRead != -1)
bytesRead = fic.read(buffer);//-------------(2)
buffer.flip();
foc.write(buffer);
buffer.compact(); //---------------(3)
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != fis) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != fos) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
说明:
2。 byteReads==-1表示输入源数据已经结束,但是buffer中仍旧还有数据。
3。在输入速度超过输出速度时,仍旧保留未输出的数据。
实现方式二:
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("c:/ntldr");
fos = new FileOutputStream("c:/ntldr.bak");
FileChannel fic = fis.getChannel();
FileChannel foc = fos.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while(fic.read(buffer)!=-1){
buffer.flip();
while(buffer.hasRemaining()){ //----------------------(1)
foc.write(buffer);
}
buffer.clear();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != fis) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != fos) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1.使用了双重循环。