2017-04-04 23 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

あなたが移動する前に、ソースファイルのパスをprintlnをしようとした – peterxz

+0

を移動されていないファイルを気づいた間違った行動に何を追加すべきか? – freedev

答えて

2

はなぜあなたのソースコードを見てみるとMoving a File or Directory

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

UPDATE

ため、このJava APIを使用していない私は、次の実装を提案する:私は管理

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

OK明らかに、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"); 
} 

みんなありがとう

関連する問題