使用 Apache Commons FileUtils 复制文件
Copying file using Apache Commons FileUtils
在第一个 运行 上,我想将给定的 File
复制到具有新文件名的新位置。
每个后续的 运行 应该覆盖第一个 运行 期间创建的相同目标文件。
在第一个 运行 期间,目标文件不存在。只有目录存在。
我写了下面的程序:
package myTest;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import org.apache.commons.io.FileUtils;
public class FileCopy {
public static void main(String[] args) {
TestFileCopy fileCopy = new TestFileCopy();
File sourceFile = new File("myFile.txt");
fileCopy.saveFile(sourceFile);
File newSourceFile = new File("myFile_Another.txt");
fileCopy.saveFile(newSourceFile);
}
}
class TestFileCopy {
private static final String DEST_FILE_PATH = "someDir/";
private static final String DEST_FILE_NAME = "myFileCopied.txt";
public void saveFile(File sourceFile) {
URL destFileUrl = getClass().getClassLoader().getResource(DEST_FILE_PATH
+ DEST_FILE_NAME);
try {
File destFile = Paths.get(destFileUrl.toURI()).toFile();
FileUtils.copyFile(sourceFile, destFile);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
}
但是,这会在以下行中抛出空指针异常:
File destFile = Paths.get(destFileUrl.toURI()).toFile();
我错过了什么?
目录someDir
直接在我项目的eclipse 根目录下。
源文件 myFile.txt
和 myFile_Another.txt
都直接存在于我项目的 eclipse 根目录下。
我使用了它,它的效果与我预期的一样:
public void saveFile1(File sourceFile) throws IOException {
Path from = sourceFile.toPath();
Path to = Paths.get(DEST_FILE_PATH + DEST_FILE_NAME);
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
}
使用 Java nio
.
在第一个 运行 上,我想将给定的 File
复制到具有新文件名的新位置。
每个后续的 运行 应该覆盖第一个 运行 期间创建的相同目标文件。
在第一个 运行 期间,目标文件不存在。只有目录存在。
我写了下面的程序:
package myTest;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import org.apache.commons.io.FileUtils;
public class FileCopy {
public static void main(String[] args) {
TestFileCopy fileCopy = new TestFileCopy();
File sourceFile = new File("myFile.txt");
fileCopy.saveFile(sourceFile);
File newSourceFile = new File("myFile_Another.txt");
fileCopy.saveFile(newSourceFile);
}
}
class TestFileCopy {
private static final String DEST_FILE_PATH = "someDir/";
private static final String DEST_FILE_NAME = "myFileCopied.txt";
public void saveFile(File sourceFile) {
URL destFileUrl = getClass().getClassLoader().getResource(DEST_FILE_PATH
+ DEST_FILE_NAME);
try {
File destFile = Paths.get(destFileUrl.toURI()).toFile();
FileUtils.copyFile(sourceFile, destFile);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
}
但是,这会在以下行中抛出空指针异常:
File destFile = Paths.get(destFileUrl.toURI()).toFile();
我错过了什么?
目录someDir
直接在我项目的eclipse 根目录下。
源文件 myFile.txt
和 myFile_Another.txt
都直接存在于我项目的 eclipse 根目录下。
我使用了它,它的效果与我预期的一样:
public void saveFile1(File sourceFile) throws IOException {
Path from = sourceFile.toPath();
Path to = Paths.get(DEST_FILE_PATH + DEST_FILE_NAME);
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
}
使用 Java nio
.