The error is telling you that either there is no File
directory relative to where you're running this, or there is but it doesn't have a handling
subdirectory. In this case, exists
returns false
and so you call createNewFile
to try to create the file, but the directory in which you're trying to create it doesn't exist, and so it throws an exception.
You can use mkdirs
to create the directories if necessary, like so:
import java.io.*;
class CreateFile{
public static void main(String[] args) throws IOException{
File f = new File("File/handling/file1.txt");
if(!f.exists()) {
f.getParentFile().mkdirs(); // This is a no-op if it exists
f.createNewFile();
}
}
}