I'm running Windows and I'm trying to refer to a directory. My function starts off like this:
File file = new File("C:\\somedir\\report");
if (!file.exists()) {
file.mkdirs();
}
doStuffWith(file);
I got a NullPointerException within the doStuffWith
function, when I tried to call listFiles
. Well I looked in C:\somedir and what did I find - there is a file called "report" with no extension, and also a directory called "report"! What seemed to happen was that the file
object was referring to the report file rather than the directory. How do I make sure that I am referring to the directory and not the file?
File file = new File("C:\\somedir\\report"); if (! file. exists()) { file. mkdirs(); } doStuffWith(file);
A file system structure containing files and other directories is called directories in java, which are being operated by the static methods in the java. nio. file. files class along with other types of files, and a new directory is created in java using Files.
In Java, we can use System. getProperty("user. dir") to get the current working directory, the directory from where your program was launched.
getRoot() method of java. nio. file. Path used to return path object of the root component of this path object or null if this path does not have a root component.
one way to go about is to pass the file object corresponding to "C:\somedir" to the method and inside the method, do a listFiles() and walk through the contents, each time checking for file name and if it is "report", do a isDirectory(). proceed with actual processing when this returns true.
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