Java file list all files in directory

Java: List Files in a Directory

A lot of applications handle files in some way and file manipulation is one of the core knowledges in any programming language.

In order to manipulate files, we need to know where they’re located. Having an overview of files in a directory is paramount if we want to accomplish this, especially if we can perform operations on them through iteration. There are several ways to do this in Java, which we’ll show throughout this article.

For the sake of simplicity, all examples will be written for the following file tree:

Programming |-- minimax.c |-- super_hack.py |-- TODO.txt `-- CodingMusic |-- Girl Talk - All Day.mp3 |-- Celldweller - Frozen.mp3 |-- Lim Taylor - Isn't It Wonderful.mp3 `-- Radiohead - Everything in Its Right Place.mp3 

File.list()

The simplest method to list the names of files and folders in a given directory, without traversing the sub-directories, is the helper method .list() , which returns an array of String s.

We do this by using the .list() method on a File instance:

public class Pathnames < public static void main(String[] args) < // Creates an array in which we will store the names of files and directories String[] pathnames; // Creates a new File instance by converting the given pathname string // into an abstract pathname File f = new File("D:/Programming"); // Populates the array with names of files and directories pathnames = f.list(); // For each pathname in the pathnames array for (String pathname : pathnames) < // Print the names of files and directories System.out.println(pathname); > > > 

Using a simple for-each loop, we iterate through the array and print out the String s.

CodingMusic minimax.c super_hack.py TODO.txt 

Using this approach, all of the items in the CodingMusic directory aren’t shown, and a downside to this approach is that we can’t really do anything to the files themselves. We’re just getting their names. It’s useful when we just want to take a look at the files at face-value.

FilenameFilter

Another thing we can do with the .list() method is to create a FilenameFilter to return only the files we want:

File f = new File("D:/Programming"); // This filter will only include files ending with .py FilenameFilter filter = new FilenameFilter() < @Override public boolean accept(File f, String name) < return name.endsWith(".py"); > >; // This is how to apply the filter pathnames = f.list(filter); 

Running this piece of code would yield:

File.listFiles()

Similar to the previous method, this one can be used to return the names of files and directories, but this time we get them as an array of File objects, which gives us the ability to directly manipulate them:

public class Pathnames < public static void main(String args[]) < // try-catch block to handle exceptions try < File f = new File("D:/Programming"); FilenameFilter filter = new FilenameFilter() < @Override public boolean accept(File f, String name) < // We want to find only .c files return name.endsWith(".c"); > >; // Note that this time we are using a File class as an array, // instead of String File[] files = f.listFiles(filter); // Get the names of the files by using the .getName() method for (int i = 0; i < files.length; i++) < System.out.println(files[i].getName()); >> catch (Exception e) < System.err.println(e.getMessage()); >> > 

Now, let’s traverse deeper into the file system using recursion and some more methods to use on the File object:

public class ListFilesRecursively < public void listFiles(String startDir) < File dir = new File(startDir); File[] files = dir.listFiles(); if (files != null && files.length > 0) < for (File file : files) < // Check if the file is a directory if (file.isDirectory()) < // We will not print the directory name, just use it as a new // starting point to list files from listDirectory(file.getAbsolutePath()); > else < // We can use .length() to get the file size System.out.println(file.getName() + " (size in bytes: " + file.length()+")"); > > > > public static void main(String[] args) < ListFilesRecursively test = new ListFilesRecursively(); String startDir = ("D:/Programming"); test.listFiles(startDir); > > 
Girl Talk - All Day.mp3 (size in bytes: 8017524) Celldweller - Frozen.mp3 (size in bytes: 12651325) Lim Taylor - Isn't It Wonderful.mp3 (size in bytes: 6352489) Radiohead - Everything in Its Right Place.mp3 (size in bytes: 170876098) minimax.c (size in bytes: 20662) super_hack.py (size in bytes: 114401) TODO.txt (size in bytes: 998) 

Files.walk()

In Java 8 and later we can use the java.nio.file.Files class to populate a Stream and use that to go through files and directories, and at the same time recursively walk all subdirectories.

Читайте также:  Get time using php

Note that in this example we will be using Lambda Expressions:

public class FilesWalk < public static void main(String[] args) < try (Stream walk = Files.walk(Paths.get("D:/Programming"))) < // We want to find only regular files List result = walk.filter(Files::isRegularFile) .map(x -> x.toString()).collect(Collectors.toList()); result.forEach(System.out::println); > catch (IOException e) < e.printStackTrace(); >> > 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Here, we’ve populated a Stream using the .walk() method, passing a Paths argument. The Paths class consists of static methods that return a Path based on a String URI — and using a Path , we can locate the file easily.

The Path , Paths , Files , and many other classes belong to the java.nio package, which was introduced in Java 7 as a more modern way to represent files in a non-blocking way.

Then, using the Collections Framework, a list is generated.

Running this piece of code will yield:

D:\Programming\Coding Music\Radiohead - Everything in Its Right Place.mp3 D:\Programming\Coding Music\Lim Taylor - Isn't It Wonderful.mp3 D:\Programming\Coding Music\Celldweller - Frozen.mp3 D:\Programming\Coding Music\Girl Talk - All Day.mp3 D:\Programming\minimax.c D:\Programming\super_hack.py D:\Programming\TODO.txt 

Conclusion

Handling files in some way is a core task for most programming languages, and this includes the ability to list and find files in the file system. In order to manipulate files, we need to know where they’re located. Having an overview of files in a directory is paramount if we want to accomplish this, especially if we can perform operations on them through iteration.

In this article we showed a number of different ways in Java to list files on the file system, using both linear and recursive approaches.

Читайте также:  Motoko

Источник

Listing All Files in a Directory in Java

Learn to use various Java APIs such as Files.list() and DirectoryStream to list all files present in a directory, including hidden files, recursively.

  • For using external iteration (for loop) use DirectoryStream .
  • For using Stream API operations, use Files.list() instead.

1. Listing Files Only in a Given Directory

1.1. Sream of Files with Files.list()

If we are interested in non-recursively listing the files and excluding all sub-directories and files in sub-directories, then we can use this approach.

  • Read all files and directories entries using Files.list().
  • Check if a given entry is a file using PredicateFile::isFile.
  • Collect all filtered entries into a List.
//The source directory String directory = "C:/temp"; // Reading only files in the directory try < Listfiles = Files.list(Paths.get(directory)) .map(Path::toFile) .filter(File::isFile) .collect(Collectors.toList()); files.forEach(System.out::println); > catch (IOException e)

1.2. DirectoryStream to Loop through Files

DirectoryStream is part of Java 7 and is used to iterate over the entries in a directory in for-each loop style.

Closing a directory stream releases any resources associated with the stream. Failure to close the stream may result in a resource leak. The try-with-resources statement provides a useful construct to ensure that the stream is closed.

List fileList = new ArrayList<>(); try (DirectoryStream stream = Files .newDirectoryStream(Paths.get(directory))) < for (Path path : stream) < if (!Files.isDirectory(path)) < fileList.add(path.toFile()); >> > fileList.forEach(System.out::println);

2. Listing All Files in Given Directory and Sub-directories

2.1. Files.walk() for Stream of Paths

The walk() method returns a Stream by walking the file tree beginning with a given starting file/directory in a depth-first manner.

Note that this method visits all levels of the file tree.

String directory = "C:/temp"; List pathList = new ArrayList<>(); try (Stream stream = Files.walk(Paths.get(directory))) < pathList = stream.map(Path::normalize) .filter(Files::isRegularFile) .collect(Collectors.toList()); >pathList.forEach(System.out::println);

If you wish to include the list of Path instances for directories as well, then remove the filter condition Files::isRegularFile.

We can also write the file tree walking logic using the recursion. It gives a little more flexibility if we want to perform some intermediate steps/checks before adding the entry to list of the files.

String directory = "C:/temp"; //Recursively list all files List fileList = listFiles(directory); fileList.forEach(System.out::println); private static List listFiles(final String directory) < if (directory == null) < return Collections.EMPTY_LIST; >List fileList = new ArrayList<>(); File[] files = new File(directory).listFiles(); for (File element : files) < if (element.isDirectory()) < fileList.addAll(listFiles(element.getPath())); >else < fileList.add(element); >> return fileList; >

Please note that if we’re working with a large directory, then using DirectoryStream performs better.

3. Listing All Files of a Certain Extention

Читайте также:  How to delete java windows

To get the list of all files of certain extensions only, use two predicates Files::isRegularFile and filename.endsWith(«.extension») together.

In given example, we are listing all .java files in a given directory and all of its sub-directories.

String directory = "C:/temp"; //Recursively list all files List pathList = new ArrayList<>(); try (Stream stream = Files.walk(Paths.get(directory))) < // Do something with the stream. pathList = stream.map(Path::normalize) .filter(Files::isRegularFile) .filter(path ->path.getFileName().toString().endsWith(".java")) .collect(Collectors.toList()); > pathList.forEach(System.out::println); >

4. Listing All Hidden Files

To find all the hidden files, we can use filter expression file -> file.isHidden() in any of the above examples.

List files = Files.list(Paths.get(dirLocation)) .filter(path -> path.toFile().isHidden()) .map(Path::toFile) .collect(Collectors.toList());

In the above examples, we learn to use the java 8 APIs loop through the files in a directory recursively using various search methods. Feel free to modify the code and play with it.

Источник

Java file list all files in directory

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью