How to see if resource file exists in Java?

flea whale picture flea whale · Feb 21, 2012 · Viewed 29.4k times · Source

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?

Answer

Johan Sjöberg picture Johan Sjöberg · Feb 21, 2012

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