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();
}
}
}
所以在用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对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- spymemcached源码中Reactor模式分析
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序