黑马程序员——————使用NIO对文件进行复制

对文件的复制有2种:1,文件复制到文件夹   2,文件复制到文件夹

1,文件复制到文件夹

package sample;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
 * @author 莫泊桑leon
 * @use 复制文件*/
//文件复制到文件
public class  Sample1{
	private static final int BSIZE = 1024;//文件缓冲字节区,大小可以自己定  
    public static void main(String [] args) throws IOException{  
		FileChannel in = new FileInputStream("C:\\新建文件夹\\1\\a.txt").getChannel();//得到输入通道  
		FileChannel out = new FileOutputStream(target).getChannel();//得到输出通道  
        ByteBuffer buffer = ByteBuffer.allocate(BSIZE);//设定缓冲区  
        while(in.read(buffer) != -1){  
            buffer.flip();//准备写入,防止其他读取,锁住文件  
            out.write(buffer);  
            buffer.clear();//准备读取。将缓冲区清理完毕,移动文件内部指针 
        } 
    }  
}
2,文件复制到文件夹

</pre><p><pre name="code" class="html">package sample;

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 Sample3 {
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		File sourceFile=new File("C:\\新建文件夹\\1\\a.txt");
		File targetFile=new File("E:/新建文件夹");
		CopyFile(sourceFile,targetFile);
	}
	public static void CopyFile(File sourceFile,File targetFile) throws IOException  {
		if(!targetFile.isFile())
			else targetFile.mkdirs();
		targetFile=new File(targetFile.getAbsolutePath()+"\\"+sourceFile.getName());
		//建立输入输出通道缓冲区
		FileChannel inChannel=new FileInputStream(sourceFile).getChannel();
		System.out.println("检测2");

		FileChannel outChannel=new FileOutputStream(targetFile).getChannel();
	
		ByteBuffer buffer=ByteBuffer.allocate(1024);
		while(inChannel.read(buffer)!=-1){
			System.out.println("检测3");
			buffer.flip();
			outChannel.write(buffer);
			buffer.clear();
		}
		inChannel.close();
		outChannel.close();
	}
}

 




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值