Java list all files in a directory

Hey guys!! Welcome to flower brackets blog. In today’s post we are going to learn java list all files in a directory.

java list all files in a directory

To list all files from a directory we are going to use class File which offers list() method which in turn returns String-array.

Also read – create directory java program

Let’s see how to get list of all file objects from a folder in java with Files.list() method,

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

public class FilesListJava 
{
   public static void main(String[] args) throws IOException
   { 
      String strName = "/project/flowerbrackets/demo/";
      Files.list(new File(strName).toPath()).limit(10)
      .forEach(path ->
      {
         System.out.println(path);
      });
   }
}

File.listFiles() Method – This program will help you to list files in a folder or directory using file input output method.

import java.io.File;

public class FileDirectoryDemo
{
public static void main(String[] args)
{
File file = null;
File paths[];

try
{
// creating new file
file = new File("/project/flowerbrackets/demo/");
paths = file.listFiles();
for(File path : paths)
{
System.out.println(path);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

Display directories in a directory with Files.walk

Let’s see traverse a directory and list all the files in java with Files.walk(). This method returns a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.
The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the relative path against start.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class FileNameFilter
{
public static void main(String[] args) throws IOException
{
try(Stream<Path> path = Files.walk(Paths.get("/project/flowerbrackets/demo/")))
{
path.filter(Files :: isRegularFile)
.forEach(System.out :: println);
}
}
}

Related Posts