tags:

views:

43

answers:

2

how to get the directory name for a particular file on the drive in java? for example i have a test.java under a test directory on my D drive.how do i find the directory name for this test.java?

+3  A: 
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.

skaffman
thanks thats wat i was lookin for
Jonathan
A: 

There is no single way to do this, however you can use the Classloader, ProtectionDomain, and CodeSource to get close.

URL url = Test.class.getProtectionDomain().getCodeSource().getLocation();
// if your Test.java is on the filesystem and not in a jar...
File testJava = new File(url.toURI());
String directory = testJava.getParent();

If it's in a jar, you'll have to parse the URL

edit: fixed a couple typos

Brian M. Carr