Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see if resource file exists in Java?

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?

like image 630
flea whale Avatar asked Feb 21 '12 15:02

flea whale


People also ask

How do I know if a file is present in classpath?

In this example we shall show you how to find a file in the classpath. To find a file in the classpath we have created a method, File findFileOnClassPath(final String fileName) that reads a fileName and returns the File.

How do you check directory is exist or not in Java?

File. exists() is used to check whether a file or a directory exists or not. This method returns true if the file or directory specified by the abstract path name exists and false if it does not exist.

Is exist in Java?

The exists() function is a part of the File class in Java. This function determines whether the is a file or directory denoted by the abstract filename exists or not. The function returns true if the abstract file path exists or else returns false. Parameters: This method does not accept any parameter.


1 Answers

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

like image 71
Johan Sjöberg Avatar answered Oct 15 '22 07:10

Johan Sjöberg