每个人都在说使用fileutils将文件从a点移动到b点是多么简单,但我在移动文件时遇到了很多问题:
我在.jar所在的目录中有一个/ temp /文件夹,在这个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();
}感谢您的帮助:\
发布于 2017-04-05 07:43:41
好吧,我设法做到了,显然getPath()方法返回了一些有趣的路径,但它在那里失败了,所以这里有一段可以工作的代码
public void downloadJar() {
String absolutePath = getPath();
String from = absolutePath + "\\temp\\test.txt";
String to = absolutePath + "\\test.txt";
File fileTo = new File(to);
File fileFrom = new File(from);
try {
FileUtils.moveFile(fileFrom, fileTo);
JOptionPane.showMessageDialog(null, "test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null, "io exce");
}
}
public String getPath() {
return System.getProperty("user.dir");
}谢谢大家
发布于 2017-04-05 07:20:51
为什么不使用这个Java API for Moving a File or Directory
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();
}https://stackoverflow.com/questions/43219245
复制相似问题