Java - How to Move Files Using Fileutils?

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 :\

8

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

ok i managed to do it, apparently the getPath() method returned some funny path and it failed there, so heres a code that works

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

thanks everyone

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.