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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With