pet*_*rxz 2 java io file move fileutils
每个人都在说使用 fileutils 将文件从 a 点移动到 b 点是多么简单,但我在移动文件时遇到了很多麻烦:(
我在 .jar 所在的目录中有一个 /temp/ 文件夹,在这个临时文件夹中我有一个 .txt 文件,我想向上移动一个目录(所以基本上在 .jar 文件旁边),但我似乎不能这样做它?
这是一些代码,但我知道它还不够接近:
public void replaceFile() {
String absolutePath = getPath();
Path from = Paths.get(absolutePath + "\\temp\\test.txt");
Path to = Paths.get(absolutePath + "\\test.txt");
try {
FileUtils.moveFile(FileUtils.getFile(from.toAbsolutePath().toString()), FileUtils.getFile(to.toAbsolutePath().toString()));
JOptionPane.showMessageDialog(null, "test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getPath() {
File jarDir = new File(ClassLoader.getSystemClassLoader().getResource(".").getPath());
//JOptionPane.showMessageDialog(null, jarDir.getAbsolutePath());
return jarDir.getAbsolutePath();
}
Run Code Online (Sandbox Code Playgroud)
任何帮助表示感谢:\
为什么不使用这个 Java API 来移动文件或目录
Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
更新
查看您的源代码我建议以下实现:
Path from = Paths.get(absolutePath, "/temp/test.txt");
Path to = Paths.get(absolutePath, "/test.txt");
try {
Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
JOptionPane.showMessageDialog(null, "test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)