文件复制实现(已经测试)
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class Copy{
public static void main(String argv[]){
if(argv.length!=2){
System.out.println("usage>java Copy srcfilename destfilename");
System.exit(0);
}
try {
// Create channel on the source
FileChannel srcChannel = new FileInputStream(argv[0]).getChannel();
// Create channel on the destination
FileChannel dstChannel = new FileOutputStream(argv[1]).getChannel();
// Copy file contents from source to destination
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
// Close the channels
srcChannel.close();
dstChannel.close();
} catch (IOException e) {
}
}
}
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class Copy{
public static void main(String argv[]){
if(argv.length!=2){
System.out.println("usage>java Copy srcfilename destfilename");
System.exit(0);
}
try {
// Create channel on the source
FileChannel srcChannel = new FileInputStream(argv[0]).getChannel();
// Create channel on the destination
FileChannel dstChannel = new FileOutputStream(argv[1]).getChannel();
// Copy file contents from source to destination
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
// Close the channels
srcChannel.close();
dstChannel.close();
} catch (IOException e) {
}
}
}
本文提供了一个使用Java进行文件复制的示例代码。通过创建源文件和目标文件的通道,并利用transferFrom方法将源文件的内容复制到目标文件中,最后关闭两个通道完成复制过程。


被折叠的 条评论
为什么被折叠?



