2017-04-04 149 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"); 
} 

感謝大家