Java access to all folders

Creating and Reading Directories

Some of the methods previously discussed, such as delete , work on files, links and directories. But how do you list all the directories at the top of a file system? How do you list the contents of a directory or create a directory?

This section covers the following functionality specific to directories:

Listing a File System’s Root Directories

You can list all the root directories for a file system by using the FileSystem.getRootDirectories method. This method returns an Iterable , which enables you to use the enhanced for statement to iterate over all the root directories.

The following code snippet prints the root directories for the default file system:

Iterable dirs = FileSystems.getDefault().getRootDirectories(); for (Path name: dirs)

Creating a Directory

You can create a new directory by using the createDirectory(Path, FileAttribute) method. If you don’t specify any FileAttributes , the new directory will have default attributes. For example:

Path dir = . ; Files.createDirectory(path);

The following code snippet creates a new directory on a POSIX file system that has specific permissions:

Set perms = PosixFilePermissions.fromString("rwxr-x---"); FileAttribute attr = PosixFilePermissions.asFileAttribute(perms); Files.createDirectory(file, attr);

To create a directory several levels deep when one or more of the parent directories might not yet exist, you can use the convenience method, createDirectories(Path, FileAttribute) . As with the createDirectory(Path, FileAttribute) method, you can specify an optional set of initial file attributes. The following code snippet uses default attributes:

Files.createDirectories(Paths.get("foo/bar/test"));

The directories are created, as needed, from the top down. In the foo/bar/test example, if the foo directory does not exist, it is created. Next, the bar directory is created, if needed, and, finally, the test directory is created.

It is possible for this method to fail after creating some, but not all, of the parent directories.

Creating a Temporary Directory

You can create a temporary directory using one of createTempDirectory methods:

The first method allows the code to specify a location for the temporary directory and the second method creates a new directory in the default temporary-file directory.

Listing a Directory’s Contents

You can list all the contents of a directory by using the newDirectoryStream(Path) method. This method returns an object that implements the DirectoryStream interface. The class that implements the DirectoryStream interface also implements Iterable , so you can iterate through the directory stream, reading all of the objects. This approach scales well to very large directories.

Remember: The returned DirectoryStream is a stream. If you are not using a try- with-resources statement, don’t forget to close the stream in the finally block. The try- with-resources statement takes care of this for you.

The following code snippet shows how to print the contents of a directory:

Path dir = . ; try (DirectoryStream stream = Files.newDirectoryStream(dir)) < for (Path file: stream) < System.out.println(file.getFileName()); >> catch (IOException | DirectoryIteratorException x) < // IOException can never be thrown by the iteration. // In this snippet, it can only be thrown by newDirectoryStream. System.err.println(x); >

The Path objects returned by the iterator are the names of the entries resolved against the directory. So, if you are listing the contents of the /tmp directory, the entries are returned with the form /tmp/a , /tmp/b , and so on.

This method returns the entire contents of a directory: files, links, subdirectories, and hidden files. If you want to be more selective about the contents that are retrieved, you can use one of the other newDirectoryStream methods, as described later in this page.

Note that if there is an exception during directory iteration then DirectoryIteratorException is thrown with the IOException as the cause. Iterator methods cannot throw exception exceptions.

Filtering a Directory Listing By Using Globbing

If you want to fetch only files and subdirectories where each name matches a particular pattern, you can do so by using the newDirectoryStream(Path, String) method, which provides a built-in glob filter. If you are not familiar with glob syntax, see What Is a Glob?

For example, the following code snippet lists files relating to Java: .class, .java, and .jar files.:

Path dir = . ; try (DirectoryStream stream = Files.newDirectoryStream(dir, "*.")) < for (Path entry: stream) < System.out.println(entry.getFileName()); >> catch (IOException x) < // IOException can never be thrown by the iteration. // In this snippet, it can // only be thrown by newDirectoryStream. System.err.println(x); >

Writing Your Own Directory Filter

Perhaps you want to filter the contents of a directory based on some condition other than pattern matching. You can create your own filter by implementing the DirectoryStream.Filter interface. This interface consists of one method, accept , which determines whether a file fulfills the search requirement.

For example, the following code snippet implements a filter that retrieves only directories:

DirectoryStream.Filter filter = newDirectoryStream.Filter() < public boolean accept(Path file) throws IOException < try < return (Files.isDirectory(path)); >catch (IOException x) < // Failed to determine if it's a directory. System.err.println(x); return false; >> >;

Once the filter has been created, it can be invoked by using the newDirectoryStream(Path, DirectoryStream.Filter) method. The following code snippet uses the isDirectory filter to print only the directory’s subdirectories to standard output:

Path dir = . ; try (DirectoryStream stream = Files.newDirectoryStream(dir, filter)) < for (Path entry: stream) < System.out.println(entry.getFileName()); >> catch (IOException x)

This method is used to filter a single directory only. However, if you want to find all the subdirectories in a file tree, you would use the mechanism for Walking the File Tree.

Источник

How to get list of all files/folders from a folder in Java?

The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.

To get the list of all the existing files in a directory this class provides the files class provides list() (returns names) and ListFiles (returns File objects) with different variants.

The List() method

This method returns a String array which contains the names of all the files and directories in the path represented by the current (File) object.

Using this method, you can just print the names of the files and directories.

Example

The following Java program lists the names of all the files and directories in the path D:\ExampleDirectory.

import java.io.File; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); //List of all files and directories String contents[] = directoryPath.list(); System.out.println("List of files and directories in the specified directory:"); for(int i=0; i> >

Output

List of files and directories in the specified directory: SampleDirectory1 SampleDirectory2 SampleFile1.txt SampleFile2.txt SapmleFile3.txt

The ListFiles() method

This method returns an array holding the objects (abstract paths) of all the files (and directories) in the path represented by the current (File) object.

Since this method returns the objects of each file/directory in a folder. Using it you can access the properties of the files/directories such as size, path etc.

Example

The following Java program prints the name, path and, size of all the files in the path D:\ExampleDirectory.

import java.io.File; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); //List of all files and directories File filesList[] = directoryPath.listFiles(); System.out.println("List of files and directories in the specified directory:"); for(File file : filesList) < System.out.println("File name: "+file.getName()); System.out.println("File path: "+file.getAbsolutePath()); System.out.println("Size :"+file.getTotalSpace()); System.out.println(" "); >> >

Output

List of files and directories in the specified directory: File name: SampleDirectory1 File path: D:\ExampleDirectory\SampleDirectory1 Size :262538260480 File name: SampleDirectory2 File path: D:\ExampleDirectory\SampleDirectory2 Size :262538260480 File name: SampleFile1.txt File path: D:\ExampleDirectory\SampleFile1.txt Size :262538260480 File name: SampleFile2.txt File path: D:\ExampleDirectory\SampleFile2.txt Size :262538260480 File name: SapmleFile3.txt File path: D:\ExampleDirectory\SapmleFile3.txt Size :262538260480

The List(FilenameFilter filter) method

As suggested in its signature, this method accepts a FilenameFilter object and returns a String array containing the names of all the files and directories in the path represented by the current (File) object. But the retuned array contains the filenames which are filtered based on the specified filter.

Using this method, you can get the filtered names of the files and directories in a particular folder.

Example

The following Java program prints the names of the text files in the path D:\ExampleDirectory.

import java.io.File; import java.io.FilenameFilter; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); FilenameFilter textFilefilter = new FilenameFilter()< public boolean accept(File dir, String name) < String lowercaseName = name.toLowerCase(); if (lowercaseName.endsWith(".txt")) < return true; >else < return false; >> >; //List of all the text files String filesList[] = directoryPath.list(textFilefilter); System.out.println("List of the text files in the specified directory:"); for(String fileName : filesList) < System.out.println(fileName); >> >

Output

List of the text files in the specified directory −

SampleFile1.txt SampleFile2.txt SapmleFile3.txt

The ListFiles(FilenameFilter filter) method

This method accepts a FilenameFilter object and returns a File array containing the objects of all the files and directories in the path represented by the current File object. But the retuned array contains the files (objects) which are filtered based on their name

Using this method, you can get the filtered file objects of the files and directories in a particular folder, according to their names.

Example

The following Java program prints the name, path and, size of all the text files in the path D:\ExampleDirectory.

import java.io.File; import java.io.FilenameFilter; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); FilenameFilter textFilefilter = new FilenameFilter()< public boolean accept(File dir, String name) < String lowercaseName = name.toLowerCase(); if (lowercaseName.endsWith(".txt")) < return true; >else < return false; >> >; //List of all the text files File filesList[] = directoryPath.listFiles(textFilefilter); System.out.println("List of the text files in the specified directory:"); for(File file : filesList) < System.out.println("File name: "+file.getName()); System.out.println("File path: "+file.getAbsolutePath()); System.out.println("Size :"+file.getTotalSpace()); System.out.println(" "); >> >

Output

List of the text files in the specified directory: File name: SampleFile1.txt File path: D:\ExampleDirectory\SampleFile1.txt Size :262538260480 File name: SampleFile2.txt File path: D:\ExampleDirectory\SampleFile2.txt Size :262538260480 File name: SapmleFile3.txt File path: D:\ExampleDirectory\SapmleFile3.txt Size :262538260480

The ListFiles(FileFilter filter) method

This method accepts a FileFilter object and returns a File array containing the (File) objects of all the files and directories in the path represented by the current File object. But the retuned array contains the files (objects) which are filtered based on the property of the file.

Using this method, you can get the filtered file objects of the files and directories in a particular folder based on the size, path, type (file or, directory) etc…

Example

The following Java program prints the name, path and, size of all the files (not folders) in the path D:\ExampleDirectory.

import java.io.File; import java.io.FileFilter; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); FileFilter textFilefilter = new FileFilter()< public boolean accept(File file) < boolean isFile = file.isFile(); if (isFile) < return true; >else < return false; >> >; //List of all the text files File filesList[] = directoryPath.listFiles(textFilefilter); System.out.println("List of the text files in the specified directory:"); for(File file : filesList) < System.out.println("File name: "+file.getName()); System.out.println("File path: "+file.getAbsolutePath()); System.out.println("Size :"+file.getTotalSpace()); System.out.println(" "); >> >

Output

List of the text files in the specified directory: File name: cassandra_logo.jpg File path: D:\ExampleDirectory\cassandra_logo.jpg Size :262538260480 File name: cat.jpg File path: D:\ExampleDirectory\cat.jpg Size :262538260480 File name: coffeescript_logo.jpg File path: D:\ExampleDirectory\coffeescript_logo.jpg Size :262538260480 File name: javafx_logo.jpg File path: D:\ExampleDirectory\javafx_logo.jpg Size :262538260480 File name: SampleFile1.txt File path: D:\ExampleDirectory\SampleFile1.txt Size :262538260480 File name: SampleFile2.txt File path: D:\ExampleDirectory\SampleFile2.txt Size :262538260480 File name: SapmleFile3.txt File path: D:\ExampleDirectory\SapmleFile3.txt Size :262538260480

Источник

Читайте также:  Java get build version
Оцените статью