Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the directory name in java

Tags:

How do I get the directory name for a particular java.io.File on the drive in Java?

For example I have a file called test.java under a directory on my D drive.

I want to return the directory name for this file.

like image 1000
Jony Avatar asked Jun 09 '10 21:06

Jony


People also ask

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.

What is directory path in Java?

A Java Path instance represents a path in the file system. A path can point to either a file or a directory. A path can be absolute or relative. An absolute path contains the full path from the root of the file system down to the file or directory it points to.

How do I get the parent directory of a file?

Use File 's getParentFile() method and String. lastIndexOf() to retrieve just the immediate parent directory.

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.


Video Answer


1 Answers

File file = new File("d:/test/test.java");
File parentDir = file.getParentFile(); // to get the parent dir 
String parentDirName = file.getParent(); // to get the parent dir name

Remember, java.io.File represents directories as well as files.

like image 121
skaffman Avatar answered Sep 22 '22 23:09

skaffman