logo

How to copy, move and delete file in Java since Java SE 7

Now I will show you how to use java.nio package to check if some file exists, how to copy, move and delete a file.

There are several ways how to work with files in Java. Either using old java.io package, or using new java.nio package and for some tasks it's easiest to use Apache Commons IO library. Now I will show you how to use java.nio package to check if some file exists, how to copy, move and delete a file:

// file exists
System.out.println("file exists? " + Files.exists(pathToFile));

Path pathToFile2 = Paths.get("file2.txt");

// move file
Files.move(pathToFile, pathToFile2, StandardCopyOption.REPLACE_EXISTING);

System.out.println("file exists? " + Files.exists(pathToFile));

// copy file
Files.copy(pathToFile2, pathToFile);

// delete file
Files.delete(pathToFile);
Files.delete(pathToFile2);

comments powered by Disqus

rss

Free online Java web application examples

Want to develop whole web applications which use database, security and more? See my github account, where are lot's of example projects:
github

Search