首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用FileUtils移动文件?

如何使用FileUtils移动文件?
EN

Stack Overflow用户
提问于 2017-04-05 07:13:27
回答 2查看 9.3K关注 0票数 2

每个人都在说使用fileutils将文件从a点移动到b点是多么简单,但我在移动文件时遇到了很多问题:

我在.jar所在的目录中有一个/ temp /文件夹,在这个temp文件夹中我有一个.txt文件,我想上移一个目录(所以基本上是在.jar文件旁边),但我似乎不能这样做?

这里有一些代码,但我知道它还不够接近:

代码语言:javascript
复制
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();
}

感谢您的帮助:\

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-04-05 07:43:41

好吧,我设法做到了,显然getPath()方法返回了一些有趣的路径,但它在那里失败了,所以这里有一段可以工作的代码

代码语言:javascript
复制
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");
}

谢谢大家

票数 2
EN

Stack Overflow用户

发布于 2017-04-05 07:20:51

为什么不使用这个Java API for Moving a File or Directory

Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);

更新

查看您的源代码,我建议使用以下实现:

代码语言:javascript
复制
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();
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43219245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档