RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Jun 4, 2021

Navigating Java Directories

In this Java programming tutorial, we delve further into navigating Java directories. This time, we will be using Java to access a directory, find its parent directory, and detail a few other its of information as well. We will be working with the java.io class to accomplish this task.

Below is sample code demonstrating how to find the parent of a file directory using Java:


import java.nio.file.*;
import java.io.*;

public class ParentOfCurrDir
	public static void main(String args[])
		ParentOfCurrDir parentOfCurrDir = new ParentOfCurrDir();
	private void proceed()
		Path currDir = Paths.get("/opt/dir1/dir2/dir3"); //A particular dir
		System.out.println("Current dir: " + currDir);
		System.out.println("Parent dir: " + currDir.getParent());
		System.out.println("Count of dir(s): " + currDir.getNameCount());
		int dirAtIndex = 2;
		System.out.println("Dir at index " + dirAtIndex + ": " + currDir.subpath(dirAtIndex,dirAtIndex+1));


If you entered this code successfully, you should get the following output. Note, your output may differ from the example, depending upon how your file folders are set up and what operating system structure you are using.

[root@mypc]# java ParentOfCurrDir
Current dir: \opt\dir1\dir2\dir3
Parent dir: \opt\dir1\dir2
Count of dir(s): 4
Dir at index 2: dir2
MS Sridhar
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date