当前位置 : 主页 > 编程语言 > java >

nio中实现文件复制的两种方式

来源:互联网 收集:自由互联 发布时间:2021-06-28
以内存映射文件的方式实现文件的复制 @Testpublic void test2() throws IOException{//直接使用open()获取文件的输入输出流FileChannel inchannel=null;FileChannel ouchannel=null;try { inchannel=FileChannel.open(Paths.g
以内存映射文件的方式实现文件的复制
@Test
	public void test2() throws IOException{
		//直接使用open()获取文件的输入输出流
		FileChannel inchannel=null;
		FileChannel ouchannel=null;
			try {
				 inchannel=FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.READ);
			     ouchannel=FileChannel.open(Paths.get("3.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE_NEW);
				//把内存中的文件直接读入缓冲区
				//创建一个缓冲区
				ByteBuffer dst=ByteBuffer.allocate(1024);
				while((inchannel.read(dst))!=-1){
					//转换成读模式
					dst.flip();
					ouchannel.write(dst);
					dst.clear();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				inchannel.close();
				ouchannel.close();
			}
			
			
			
	}
网友评论