您的位置:首页 > 编程语言 > Java开发

java NIO复制文件

2016-01-11 22:06 423 查看
java NIO是在JDK1.4之后才有的机制,与传统IO不同的是,NIO采用了新的方法,提供了非阻塞I/O,使得性能有了很大的提升。

所以在用NIO复制文件的时候,效率会比IO要高许多,当复制的文件越大,效果越明显

以下,是实现把D盘下的text.pdf复制到D盘下并命名为text2.pdf的代码

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NioTest {
public static void main(String[] args) {
File f1=new File("D:"+File.separator+"text.pdf");//源文件名
File f2=new File("D:"+File.separator+"text2.pdf");//目标文件
FileInputStream in=null;
FileOutputStream out=null;
try{
in=new FileInputStream(f1);
out=new FileOutputStream(f2);
FileChannel channel1=in.getChannel();//开辟输入文件通道
FileChannel channel2=out.getChannel();//开辟输出文件通道
ByteBuffer buffer=ByteBuffer.allocate(1024);//缓冲
int temp=0;
while((temp=channel1.read(buffer))!=-1){
buffer.flip();
channel2.write(buffer);
buffer.clear();//清空缓冲区
}
channel1.close();
channel2.close();
out.close();
in.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java io nio