第1个回答 2008-10-16
将"中国农民贫穷的真正原因.txt"复制到("d:/MYJAVADemo/fileCopyDemo.txt"
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class FileCopyDemo {
public static void main(String[] args) {
File dir = new File("d:/MYJAVADemo/");
if (dir.exists()) {
System.out.println("目录己经存在: ");
} else {
if (dir.mkdirs()) {
System.out.println("目录生创建成功: ");
} else {
System.out.println("目录生成失败,系统异常退出: ");
System.exit(1);
}
}
File file = new File(dir, "fileCopyDemo.txt");
File file1 = new File(dir, "中国农民贫穷的真正原因.txt");
FileOutputStream fos = null;
FileInputStream fis = null;
try {
fos = new FileOutputStream(file);
fis = new FileInputStream(file1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileChannel filechannel1 = fos.getChannel();
FileChannel filechannel2 = fis.getChannel();
try {
filechannel1.transferFrom(filechannel2, 0, filechannel2.size());
//注意这个方法,输出文件管道向输入文件管道读取数据;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (filechannel1 != null) {
try {
filechannel1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (filechannel2 != null) {
try {
filechannel2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
第3个回答 2019-05-13
FileChannel inchannel=FileChannel.open(Paths.get("1.mkv"), StandardOpenOption.READ);
FileChannel outchannel=FileChannel.open(Paths.get("2.mkv"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
inchannel.transferTo(0, inchannel.size(), outchannel);