How to use Files.move with Java?

Asked

Viewed 200 times

0

I have created a photo upload on my system, these photos are saved in a temp , I need to move them to a default directory, other than temp.

This is the method that creates the directory :

public FotoStorageLocal() {
    //Versao MAC
    //this(getDefault().getPath(System.getenv("user.home"), ".genesisfotos"));

    // versao windows
    this(getDefault().getPath(System.getProperty("user.home"), ".genesisfotos"));
        System.out.println(">>>>>>>> CRIADO GENESIS + FOTOS ");
}

public FotoStorageLocal(Path path) {
    this.local = path;
    criarPastas();
}

And this is the method that makes the photo be saved and then transferred from the temp folder to the standard directory.

I run the system but it can not take the photo of the folder has to another folder, follow code

public void salvar(String foto) {
    try {
        Files.move(this.localTemporario.resolve(foto), this.local.resolve(foto));
    } catch (IOException e) {
        throw new RuntimeException("Erro movendo a foto para destino final", e);
    }
    try {
        Thumbnails.of(this.local.resolve(foto).toString()).size(40, 68).toFiles(Rename.PREFIX_DOT_THUMBNAIL);
    } catch (IOException e) {
        throw new RuntimeException("Erro gerando thumbnail", e);
    }
}

1 answer

0

The use of the method Files.move() is:

Path sourcePath      = Paths.get("data/logging-copy.properties");
Path destinationPath = Paths.get("data/subdir/logging-moved.properties");

try {
    Files.move(sourcePath, destinationPath,
            StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    e.printStackTrace();
}

Note that they are used as parameters (Path source, Path target, CopyOption... options). Make sure the method Files.move(this.localTemporario.resolve(foto), this.local.resolve(foto)); is using the method correctly

  • Good evening Thank you, first of all for the attention, I made the changes but even so I can’t move the temp file to the directory above, I will put the class in Pastebin can help me?

  • Yes, insert the code by editing the question or paste the link in the comment please.

  • Follow the code Gaspar - https://pastebin.com/XzJVsj5y

  • Try putting the code on line 53: Path sourcePath = localTemporario.resolve(foto);
Path destinationPath = local.resolve(foto);
Files.move(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);

  • I tried what you told me but still the photo remains only in temp, it is not on a directory, the images continue only in temp, the folders are like this: C: Users BRUNO.genesisfotos temp, the right would be to return a directory : C: Users BRUNO.genesisfotos\

  • Gaspar managed to solve the error, was missing in the save method a parameter, thank you very much for the help , I work with your tips.

  • Thanks @Brunexx! I’m happy to help

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.