Java 8 copy, move and delete files

Problem

In java 8 working with files is easy and secure by using NIO.2. Below you can find the most frequent operations.

Solution Move files

In java 8 files can be moved by Files.move(). Moving a file is similar to renaming it, except that folder is changed and not the name. If the destination file already exists, then exception is thrown:

java.nio.file.FileAlreadyExistsException :

Path source  = Paths.get("C://user//myfile.txt");
Path target = Paths.get("C://user//folder//myfile.txt");

try {
    Files.move(source, destination);
} catch(FileAlreadyExistsException fae) {
    fae.printStackTrace();
} catch (IOException e) {
    // something else went wrong
    e.printStackTrace();
}

Overwriting an existing file can be done by :

Files.move(source, destination, StandardCopyOption.REPLACE_EXISTING);

Solution Copy files with NIO.2

Copying files is done by Files.copy() method copies a file from one path to another. If the destination file already exists, then exception is thrown:

java.nio.file.FileAlreadyExistsException:

Path source  = Paths.get("myfile.csv");
Path target = Paths.get("myfile-copy.csv");

try {
    Files.copy(source, destination);
} catch(FileAlreadyExistsException fae) {
    fae.printStackTrace();
} catch (IOException e) {
    // something else went wrong
    e.printStackTrace();
}

Solution Delete files

Deleting is done by Files.delete(). It can delete a file or directory(it will only delete a directory if it is empty.):

Path path = Paths.get("deleteme.txt");
try {
    Files.delete(path);
} catch (IOException e) {
    // deleting failed
    e.printStackTrace();
}

If you want more about files and java 8 :

java 8 iterate check and read files/

Related Article