gpt4 book ai didi

Java - 如何使用 FileUtils move 文件?

转载 作者:行者123 更新时间:2023-11-29 04:32:36 27 4
gpt4 key购买 nike

每个人都在说使用 fileutils 将文件从 a 点 move 到 b 点是多么简单,但我在 move 文件时遇到了很多麻烦:(

我在 .jar 所在的目录中有一个/temp/文件夹,在这个临时文件夹中我有一个 .txt 文件我想向上 move 一个目录(所以基本上在 .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();
}

感谢任何帮助:\

最佳答案

为什么不将此 Java API 用于 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();
}

关于Java - 如何使用 FileUtils move 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43219245/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com