38

I am trying to output text to a resource file in Java like so:

File file = new File(MLM.class.getClassLoader().getResource("mazes.txt").toString());
BufferedWriter out = new BufferedWriter(new FileWriter(file));
..

but because the resource file has not been created I get a null pointer exception. How can I create a blank resource file first if it doesn't exist already to avoid this error?

Lucas Prestes
  • 362
  • 1
  • 4
  • 19
flea whale
  • 1,783
  • 3
  • 25
  • 38
  • Please check this post: http://stackoverflow.com/questions/1816673/how-do-i-check-if-a-file-exists-java-on-windows – adis Feb 21 '12 at 16:00

2 Answers2

59

A simple null check would suffice

URL u = MLM.class.getResource("/mazes.txt");
if (u != null) {
         ...
}

From the javadoc for getResource

Returns:
A URL object or null if no resource with this name is found

Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
0

You can use before your code :

File.createNewFile()

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.

Sandro Munda
  • 39,921
  • 24
  • 98
  • 123