对文件的复制有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();
}
}