是否有标准的 Java 库来处理常见的文件操作,例如 move/复制文件/文件夹?
最佳答案
以下是使用 java.nio
操作的方法:
public static void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
// previous code: destination.transferFrom(source, 0, source.size());
// to avoid infinite loops, should be:
long count = 0;
long size = source.size();
while((count += destination.transferFrom(source, count, size-count))<size);
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
}
关于java - Java 中的 move/复制文件操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/300559/