Java Files  «Prev  Next»
Lesson 8 Working with files
Objective Explore how to move, rename, and delete files.

Creating files

Java 2 adds the createNewFile() method:
public boolean createNewFile() throws IOException // Java 2

This method checks to see whether the file exists and creates the file if it does not already exist.
It returns true if the file was created and false if it wasn't created, either because it couldn't be created or because the file already existed. For example:
File f = new File("output.dat");
boolean success = f.createNewFile();
if (success) {
else {

This method throws an IOException if an I/O error occurs. It throws a security exception if the security manager vetoes the creation of the file.
There are several methods in the File class that allow you to manipulate files:
  1. renameTo()
  2. delete()

The File class also contains the usual equals(), hashCode(), and toString() methods, which behave exactly as you would expect. The File class does not contain a clone() method.