Java Functional Programming (11): Traversing directory _java

Source: Internet
Author: User
Tags anonymous

Listing files in a directory

The list () method of the file class makes it easy to list the file names of all the files in the directory. You can use its listfiles () method if you want to get a file, not just a filename. This is very simple and difficult is how to deal with the return of the list. Instead of using the traditional verbose external iterator, we use elegant functional expressions to actually traverse the list. Here we also have to use the new Closeablestream interface of JDK and some related high-order functions.

The following code can list the names of all the files in the current directory.

Copy Code code as follows:

Files.list (Paths.get ("."))
. ForEach (System.out::p rintln);

If you want to list other catalogs, you can put "." Replaces the full path of the directory to which Chengxiang is accessing.

This first uses the paths get () method and creates a path instance with a string. Then we get a Closablestream object through the list () method of the Files tool class, which we can use to traverse all the files in the directory. We then use the internal iterator foreach () to print out the file name. Let's take a look at some of the output from this code: list the files and subdirectories in the current directory.

Copy Code code as follows:

./asamplefiles.txt
./bin
./fpij
...

If we only want to get subdirectories of the current directory, instead of files, we can use the filter () method:

Copy Code code as follows:

Files.list (Paths.get ("."))
. Filter (Files::isdirectory)
. ForEach (System.out::p rintln);

The Ilter () method filters the directory from the file stream. Instead of passing a lambda expression, we pass a reference to the Isdirectory method of the Files class. Recall that the filter () method requires a predicate type that returns a Boolean value, which is exactly the right way to do it. Finally, we use an internal iterator to print out the directory name. The program will print out subdirectories of the current directory.

Copy Code code as follows:

./bin
./fpij
./output
...

This is much simpler to write, compared to the Java old way to save a lot of code. Let's look at how to list the files that match a pattern.

Lists the files specified under the directory

Java has earlier provided a variant of the list () method for filtering file names. This version of the list () method accepts an argument of the FilenameFilter type. This interface has only one accept () method, which accepts two parameters: File Dir (representing the directory), and string name (representing the file name). If the Accept () method returns True, the filename will appear in the returned list, and false will not be returned. Let's implement this method.

The habitual practice is to pass an instance of an anonymous inner class that implements the FilenameFilter interface to the list () method. For example, let's look at how to return the. java file in the Fpij directory in this way.

Copy Code code as follows:

Final string[] Files =
New File ("Fpij"). List (new Java.io.FilenameFilter () {
Public Boolean accept (Final File dir, final String name) {
Return Name.endswith (". Java");
}
});
System.out.println (files);

It's really going to take some time to write a few lines of code. This code is too noisy: create objects, call functions, define anonymous inner classes, embed methods inside classes, and so on. We don't have to endure the pain anymore, just pass in a lambda expression that takes two parameters and returns Bollean. The Java compiler will take care of the rest.

The previous example can simply replace anonymous interiors with a lambda expression, but there is room for further optimization. The new Directorystream tool can help us to traverse large directory structures more efficiently. Let's try this method. This is a variant of the Newdirectorystream () method, which accepts an additional filter.

Copy Code code as follows:

Files.newdirectorystream (
Paths.get ("Fpij"), Path-> path.tostring (). EndsWith (". Java")
. ForEach (System.out::p rintln);

This removes the anonymous inner class and makes the cumbersome code simple and straightforward. The output of these two versions is the same. Let's print the file specified below.

This code only outputs the. java file in the specified directory, and the following is part of its output:

Copy Code code as follows:

Fpij/compare.java
Fpij/iteratestring.java
Fpij/listdirs.java
...

We filter files based on file names, and it's also easy to filter through file properties, such as whether the file is executable, readable, writable, and so on. To do so requires a listfiles () method that takes a filefilter type of argument. We still use lambda expressions to implement rather than create anonymous inner classes. Now let's look at an example that lists all the hidden files in the current directory.

Copy Code code as follows:

Final file[] files = new File ("."). Listfiles (File-> file.ishidden ());

If we're working with a large directory, we can use Directorystream instead of calling the method directly above the file.

The signature of the lambda expression we pass to the Listfiles () method is the same as the signature of the Accept () method of the FileFilter interface. This lambda expression accepts the argument of a file instance in which the parameter name is file. Returns true if the file is a hidden property, or false.

In fact, we can also streamline the code, we do not pass the lambda expression, passing a method reference will make the code look more concise:

Copy Code code as follows:

New File ("."). Listfiles (File::ishidden);

We implement the lambda expression first, and then use the method reference to refactor it more succinctly. If we write new code again, of course we should adopt this concise approach. If we can find this simple implementation early, of course we have to use it first. There is a phrase called "Let it work first, then to optimize (make it work, then made it better)", first let the code run, and so we understand, to consider simplicity and performance optimization.

We use an example to filter out the specified file from the directory. Let's look at how to traverse the subdirectories in the specified directory.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.