Search code examples
javafileiomovefileutils

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


Solution

  • 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