Java print directory listing

Java Program to List Files and Folders in Directory

This article covers a program in Java, that list and print all files and folders available in a directory.

Java Get Files and Folders in a Directory

The question is, write a Java program to print all files and folders available in a directory. The program given below is its answer:

import java.io.File; public class CodesCracker < public static void main(String[] args) < String directory = "C:\\Users\\DEV\\Documents\\NetBeansProjects\\CodesCracker"; File fileObject = new File(directory); String[] filesFolders = fileObject.list(); System.out.println("---List of Files and Folders---"); for(String ff: filesFolders) System.out.println(ff); > >

The snapshot given below shows the sample output produced by above Java program. This output shows all the files and folder available in the directory given to the variable directory:

java list files in directory

In above output, all files and folders are printed in organized way. Organized means, files and folders both are in alphabetical order. Here is the snapshot of the directory, given to above program:

java get files in directory

Java Get all Files and Folders in a Given Directory

Here is the modified version of previous program. This program allows user to enter the directory, of which, he/she wants to find and print all files and folders:

import java.util.*; import java.io.*; public class CodesCracker < public static void main(String[] args) < String directory; Scanner scan = new Scanner(System.in); System.out.print("Enter the Directory: "); directory = scan.nextLine(); File fileObject = new File(directory); String[] filesFolders = fileObject.list(); System.out.println("\n---List of all Files and Folders---"); for(String ff: filesFolders) System.out.println(ff); > >

The snapshot given below shows the sample run of above program with user input C:\Users\DEV\Documents\cpp programs as directory, to print all files and folders available in this directory:

java get all files in given directory

And here is the snapshot of the directory C:\Users\DEV\Documents\cpp programs:

java find print all files in given directory

Java Get all Files and Folders in Directory and Sub-directories

To get and print all files and folders available in current directory and its sub-directories, then use the program given below:

import java.util.*; import java.io.*; public class CodesCracker < public static void main(String[] args) < if(args.length == 0) args = new String[] "..">; ListString> nextDir = new ArrayListString>(); nextDir.add(args[0]); try < while(nextDir.size() > 0) < File pathName = new File(nextDir.get(0)); // gets the element at the index of List String[] fileNames = pathName.list(); // lists all the files in the directory for(int i=0; ilength; i++) < // getPath converts abstract path to path in String, // constructor creates a new File object with fileName name File f = new File(pathName.getPath(), fileNames[i]); if(f.isDirectory()) < System.out.println(f.getCanonicalPath()); nextDir.add(f.getPath()); > else System.out.println(f); > nextDir.remove(0); > > catch(IOException ioe) < System.out.println("\nException: " +ioe); > > >

The output produced by this program will be the list of all files and folders available in the current directory and its sub-directories. The files and folders are listed along with full path, to understand, files or folders are of which directory. The snapshot given below shows a part of the sample output produced by above program.

Читайте также:  HTML размер шрифта

java list files folders in directory sub directories

A lot of files and folders available inside the current directory in my case, therefore it is not possible to show the complete output in single snapshot. But the thing is, you’ll get the similar output.

Same Program in Other Languages

Liked this article? Share it!

Источник

Java list directory contents

Java list directory tutorial shows how to display directory contents in Java.

Directory definition

is an organizing unit in a computer’s file system for storing and locating files. Directories are hierarchically organized into a tree of directories. Directories have parent-child relationships.

Java list directory classes

List directory contents non-recursively with Files.list

The Files.list method returns a lazily populated stream of Path objects. The listing is not recursive.

package com.zetcode; import java.io.File; import java.io.IOException; import java.nio.file.Files; public class JavaFilesList < public static void main(String[] args) throws IOException < String dirName = "/home/janbodnar/prog/"; Files.list(new File(dirName).toPath()) .limit(10) .forEach(path ->< System.out.println(path); >); > >

This example displays ten files or directories from the given directory.

List directory contents recursively with Files.walk

The Files.walk method returns a lazily populated stream of Paths by walking the file tree rooted at a given starting file. Files.walk recursively walks all subdirectories.

package com.zetcode; 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 JavaFilesWalkFilter < public static void main(String[] args) throws IOException < try (Streampaths = Files.walk(Paths.get("/home/janbodnar/prog"))) < paths.filter(Files::isRegularFile) .forEach(System.out::println); >> >

This example displays the contents of the given directory with Files.walk method. With the filter method, we filter the contents of the directory to include only regular files.

Listing directory contents non-recursively with Files.walkFileTree

Files.walkFileTree method walks a file tree rooted at a given starting file. It uses a FileVisitor pattern which specifies the required behavior at key points in the traversal process: when a file is visited, before a directory is accessed, after a directory is accessed, or when a failure occurs.

package com.zetcode; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; public class JavaWalkFilesTree < public static void main(String[] args) throws IOException < String dirName = "/home/janbodnar/prog"; File file = new File(dirName); Files.walkFileTree(file.toPath(), Collections.emptySet(), 1, new SimpleFileVisitor() < @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException < System.out.println(file); return FileVisitResult.CONTINUE; >>); > >

The example uses Files.walkFileTree to traverse a directory non-recursively.

Files.walkFileTree(file.toPath(), Collections.emptySet(), 1, new SimpleFileVisitor() 

The Files.walkFileTree parameters are: the starting file, the options to configure the traversal, the maximum number of directory levels to visit, the file visitor to invoke for each file. In our case we have one directory level to traverse.

Listing directory contents recursively with Files.walkFileTree

In the following example, we use Files.walkFileTree to traverse the whole directory structure.

package com.zetcode; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; public class JavaWalkFilesTree < public static void main(String[] args) throws IOException < String dirName = "/home/janbodnar/prog"; File file = new File(dirName); Files.walkFileTree(file.toPath(), new SimpleFileVisitor() < @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException < System.out.println(file); return FileVisitResult.CONTINUE; >>); > >

The example uses an overloaded Files.walkFileTree method to traverse a directory recursively.

Listing directory contents non-recursively with File

The java.io.File class is an older API to list directory contents. It is not as powerful as the modern API, mentioned earlier. The File's listFiles returns an array of file objects in the given directory.

package com.zetcode; import java.io.File; public class JavaDirectoryContentsFile < public static void main(String[] args) < String dirName = "/home/janbodnar/tmp/"; File fileName = new File(dirName); File[] fileList = fileName.listFiles(); for (File file: fileList) < System.out.println(file); >> >

The example prints the contents of the given directory to the console. It does not go into subdirectories.

Listing directory contents recursively with File

This time we use java.io.File class to recursively list the directory.

package com.zetcode; import java.io.File; import java.util.ArrayList; import java.util.List; public class JavaDirectoryContentsFileRecursive < private static Listfiles = new ArrayList<>(); public static void main(String[] args) < String dirName = "/home/janbodnar/tmp/"; File file = new File(dirName); Listmyfiles = doListing(file); myfiles.forEach(System.out::println); > public static List doListing(File dirName) < File[] fileList = dirName.listFiles(); for (File file : fileList) < if (file.isFile()) < files.add(file); >else if (file.isDirectory()) < files.add(file); doListing(file); >> return files; > >

The doListing method lists the contents of a directory. We determine if the file is a directory with isDirectory method and recursively call doListing on each subdirectory.

Listing directory contents with Apache commons IO

Apache commons' FileUtils.listFiles allows to list directory contents both recursively and non-recursively.

For the example we need this dependency.

package com.zetcode; import java.io.File; import java.util.List; import org.apache.commons.io.FileUtils; public class JavaDirectoryContentsApacheCommons < public static void main(String[] args) < String dirName = "/home/janbodnar/tmp/"; Listfiles = (List) FileUtils.listFiles(new File(dirName), null, true); files.forEach(System.out::println); > >

The code example displays the directory contents recursively with FileUtils.listFiles .

List files = (List) FileUtils.listFiles(new File(dirName), null, true);

The first parameter of the FileUtils.listFiles is the directory name to be listed. The second parameter is the array of extensions that should match the listing. If null is given, all files are returned. The third parameter determines if the listing is recursive; that is, all subdirectories are searched as well.

In this article we have shown various ways to list directory contents in Java.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

Java program to print all files and folders in a directory in sorted order

In this tutorial, we will print out all files and folders of a directory in sorted order using Java. To run this program, you will have to change the directory name defined inside ‘main’ method.

Create a new ‘File’ object by passing the scanning directory name to its constructor

Get list of all files and folders using ‘listFiles()’ method

Sort the list using ‘Arrays.sort()’ method

Now , using a ‘for-loop’, iterate through this list and get the name of each file or folder using ‘getName()’

If it is a file, we are printing ‘File ’ before the file name and if it is a folder we are printing ‘Directory :‘.

/* * Copyright (C) 2017 codevscolor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.util.Arrays; /** * Example class */ public class ExampleClass  //utility method to print a string static void print(String value)  System.out.println(value); > /** * Method to sort all files and folders in a directory * * @param dirName : directory name * @return : No return value. Sort and print out the result */ private static void sortAll(String dirName)  File directory = new File(dirName); File[] filesArray = directory.listFiles(); //sort all files Arrays.sort(filesArray); //print the sorted values for (File file : filesArray)  if (file.isFile())  print("File : " + file.getName()); > else if (file.isDirectory())  print("Directory : " + file.getName()); > else  print("Unknown : " + file.getName()); > > > public static void main(String[] args)  sortAll("C://Programs/"); > > 

Источник

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