Subdirectories Java Exercise - Java Programming Course

 Exercise

Subdirectories

 Objetive

Create a program to store the files that are located in a particular folder and its subfolders.

Then, it will ask the user which text to search and it will display the files containing that text in their name.

Program will end when the user enters an empty search string.

 Example Code

import java.util.*;
public class Main
{
	static void main(String[] args)
	{
		try
		{
			String text = "";

			System.out.print("Enter a directory for search: ");
			text = new Scanner(System.in).nextLine();

			while (!text.equals(""))
			{
				java.io.File directory = new java.io.File(text);

				// Save files and directories
				java.io.File[] files = directory.GetFiles("*.*");
				java.io.File[] directories = directory.GetDirectories();

				// Write the files
				int i = 0;
				for (; i < files.length; i++)
				{
					System.out.println(((java.io.File)files[i]).getPath());
				}

				// Write the directories
				for (i = 0; i < directories.length; i++)
				{
					System.out.println(((java.io.File)directories[i]).getPath());
				}

				System.out.print("\nEnter a directory for search: ");
				text = new Scanner(System.in).nextLine();
			}
		}
		catch (RuntimeException ex)
		{
			System.out.println(ex.toString());
		}
	}
}


Juan A. Ripoll - Programming Tutorials and Courses © 2024 All rights reserved.  Legal Conditions.