Java文件拷贝
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class CopyTest {
public static void main(String[] args) throws IOException {
String src = "E:\\1.txt";
String target = "E:\\2.txt";
copyByNIO2(src,target);
}
private static void copyByBIO(String src,String target) throws IOException {
File file = new File(src);
FileInputStream fileInputStream = new FileInputStream(file);
File file1 = new File(target);
FileOutputStream fileOutputStream = new FileOutputStream(file1);
int b =0;
while((b=fileInputStream.read())!=-1){
fileOutputStream.write(b);
System.out.println(b);
}
fileInputStream.close();
fileOutputStream.close();
}
private static void copyByNIO(String src,String target)throws IOException{
File file = new File(src);
FileInputStream fileInputStream = new FileInputStream(file);
FileChannel channel = fileInputStream.getChannel();
File file1 = new File(target);
FileOutputStream fileOutputStream = new FileOutputStream(file1);
FileChannel channel2 = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int)file.length());
channel.read(byteBuffer);
byteBuffer.flip();
channel2.write(byteBuffer);
channel2.close();
fileOutputStream.close();
channel.close();
fileInputStream.close();
}
private static void copyByNIO2(String src,String target)throws IOException{
FileInputStream fileInputStream = new FileInputStream(new File(src));
FileChannel channel = fileInputStream.getChannel();
FileOutputStream fileOutputStream = new FileOutputStream(new File(target));
FileChannel channel2 = fileOutputStream.getChannel();
channel2.transferFrom(channel,0,channel.size());
channel2.close();
fileOutputStream.close();
channel.close();
fileInputStream.close();
}
}