dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Jun 3, 2021

Listing Directory Files Using Java

This quick Java tutorial shows you how to use streams to find .java files in a given directory. The code can, of course, be altered to show any file types in a directory (or even multiple types). Here is the sample code to achieve this. Feel free to change the line:

String fileTypes = "*.java"; 

To other file types. For instance, you could also change it to find Word documents by altering it to:

String fileTypes = "*.docx";

Here is the Java code showing how to list directory files of a certain type:

*/

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

public class ListFilesInDirUsingStreams
{
	public static void main(String args[])
	{
		ListFilesInDirUsingStreams listFilesInDirUsingStreams = new ListFilesInDirUsingStreams();
		listFilesInDirUsingStreams.proceed();
	}
	
	private void proceed()
	{
		Path currDir = Paths.get("."); //Current directory
		String fileTypes = "*.java";
		
		try (DirectoryStream directoryStream = 
			Files.newDirectoryStream(currDir, fileTypes)) {
			System.out.println("Files of type " + fileTypes + " in " + currDir);
			for (Path fileInPath: directoryStream) {
				System.out.println(fileInPath);
			}
		}catch (IOException ioe) {
			System.out.println(ioe);
		}
	}
}

/*

You could expect output similar to the following. Note: your output will be differen depending upon which files you have in your directory:

[root@mypc]# java ListFilesInDirUsingStreams
Files of type *.java in .
.\CurrentThreadDumpStack.java
.\FilePermissionsEx.java
.\ListFilesInDirUsingStreams.java
.\ParentOfCurrDir.java
.\SavepointEx.java
.\SupportedCharsets.java
MS Sridhar
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date