2017-04-04 177 views
1

大家一直说使用fileutils将文件从a点移动到b点有多简单,但是我在移动文件时遇到了很多问题:(Java - 如何使用FileUtils移动文件?

我在目录中有一个/ temp /文件夹.jar位于此临时文件夹中,我有一个.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(); 
} 

任何帮助表示赞赏:\

+1

您应该添加什么是错误的行为,你已经注意到 – freedev

+0

没有被移动 – peterxz

+0

假如你尝试过此举给println源文件的路径的文件? – freedev

回答

2

为什么不使用Java API来Moving a File or Directory

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

UPDATE

看你的源代码,我建议以下实现:

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(); 
} 
+0

试过了,没有工作 – peterxz

+0

你能举个例子吗?看我在哪里搞砸 – peterxz

+0

我已经更新了我的答案。我已经在我的机器上本地尝试过这个版本,如果源和目标路径正确无误。 – freedev

1

确定我设法做到这一点,显然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"); 
} 

感谢大家