Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to move files using FileUtils?

Everyone keeps saying how simple it is to move a file from point a to point b using fileutils, but I'm having lots of trouble moving a file :(

I have a /temp/ folder in the directory wherever the .jar is located, in this temp folder I have a .txt file I want to move up a directory (so basically next to the .jar file) but I cant seem to do it?

Here's some code, but I know its not even close:

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

Any help is appreciated :\

like image 286
peterxz Avatar asked Apr 16 '26 21:04

peterxz


1 Answers

Why don't use this Java API for Moving a File or Directory

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

UPDATE

Looking at your source code I suggest the following implementation:

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();
}
like image 120
freedev Avatar answered Apr 19 '26 09:04

freedev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!