Monday, June 7, 2010

When Java create an actual file

It has been a long time that I thought "File file = new File("readme.txt")" will create an actual file called "readme.txt". Obviously, I was wrong and the consequent codes always blew up with a NullPointerException or IOException saying file or directory not found.

After a bit googling, I figured out the whole thing and wanted to share the thing I know.

There are two ways to create actual files in Java:
  • create a file explicitly with method createNewFile() from a File object:
file.createNewFile();
Even though the method called "createNew...", but it doesn't have to be a file non-existed. I mean it will just ignore the creation if the file is existing.

  • initialising a Writer or Stream, for example, PrintWriter with the file as passed-in parameter will create an actual file:
PrintWriter writer = new PrintWriter(file);

That looks easy. But how about directory creation. Do you think the following codes will work out assuming that the "javaCoffee" directory isn't there?

File dir = new File("javaCoffee");
File file = new File(dir, "bean.txt");
file.createNewFile();

Looks good but unfortunately, the last line will throw an IOException saying "No such file or directory". When creating a directory, you have to explicitly invoke "mkDir()" before creating any files inside the folder, even though you specified the absolute path like: "File file2 = new File("C:/javaCoffee/bean.txt")". It will throw an FileNotFoundException.


This is easy as well once you know it.

No comments: