Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I refer to a directory in Java?

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?

like image 545
Adam Burley Avatar asked Jan 28 '10 12:01

Adam Burley


People also ask

How do you reference a directory in Java?

File file = new File("C:\\somedir\\report"); if (! file. exists()) { file. mkdirs(); } doStuffWith(file);

What is directory in Java example?

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.

How do I find my Java working directory?

In Java, we can use System. getProperty("user. dir") to get the current working directory, the directory from where your program was launched.

How do I get to root directory in Java?

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.


1 Answers

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.

like image 90
Aadith Ramia Avatar answered Sep 22 '22 21:09

Aadith Ramia