Walking filesystem from Java console

This is small example of walking over filesystem from console:

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
import java.util.Spliterator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

class DirectoryList{

	public static void main(String[] args) throws IOException {

		Scanner scanner = new Scanner(System.in);
		Path selectedPath = null;

		while (true){

			//get all paths in current selected directory
			List<Path> selectFromPath = getDirList(selectedPath).collect(Collectors.toList());


			for(int i=0; i<selectFromPath.size(); i++){
				System.out.println(i + " : " + selectFromPath.get(i));

			System.out.print("\nEnter choice (ENTER TO EXIT) > ");
			//select path matching line number
			String choice = scanner.nextLine();

			if(choice.isEmpty()) break;

			//load that path inside selectFromPath using line number as index
			selectedPath = selectFromPath.get(Integer.parseInt(choice));



	private static Stream<Path> getDirList(Path path) throws IOException {
		if(path == null){
			//if path is null, get initial drive list in windows (or root in linux)
			Spliterator<Path> pathSpliterator = FileSystems.getDefault().getRootDirectories().spliterator();
			return StreamSupport.stream(pathSpliterator, false);
		//include path for walking one level up from current "path"
		Path previousPath = path.resolve(Paths.get("..")).normalize();
		//include path for previous level (..) and all paths in the current "path" directory
		return Stream.concat(Stream.of(previousPath.equals(path) ? null : previousPath), Files.walk(path, 1));


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s