Directory list Device

Source: Internet
Author: User
Tags filter anonymous final sort

Now suppose we want to view a list of directories. You can list the file objects in two ways. Calling list () without arguments (parameters) obtains a complete list contained in the file object. However, if you want to make certain restrictions on this list, you need to use a "directory filter" that indicates how the file object should be selected to complete the display.
Here is the code for this example (or if you are having difficulty executing the program, refer to Chapter 3rd 3.1.2 subsection "assignment"):

: Dirlist.java
//Displays directory listing
package c10;
Import java.io.*;

public class Dirlist {public
  static void Main (string[] args) {
    try {
      File path = new File (".");
      string[] list;
      if (Args.length = = 0)
        list = Path.list ();
      else 
        list = path.list (new Dirfilter (args[0));
      for (int i = 0; i < list.length i++)
        System.out.println (list[i);
    } catch (Exception e) {
      E.printstacktrace ();

}} Class Dirfilter implements FilenameFilter {
  String AFN;
  Dirfilter (String afn) {This.afn = AFN;}
  Public Boolean Accept (File dir, String name) {
    //Strip path information:
    String f = new File (name). GetName (); 
   return F.indexof (AFN)!=-1;
  }
} ///:~


The Dirfilter class "implements" The interface FilenameFilter (questions about interfaces, which are detailed in chapter 7th). Let's look at how simple the FilenameFilter interface is:

Public interface FilenameFilter {
Boolean Accept (file directory, string name);
}

It indicates that all objects of this type provide a method named Accept (). The whole reason for creating such a class is to provide the accept () method to the list () method so that the list () can "callback" accept () to determine which file names should be included in the list. Therefore, this technique is often referred to as a "callback", sometimes called an "operator" (that is, Dirfilter is an operator because its only function is to hold a method). Since list () uses a FilenameFilter object as its own variable, we can pass an object of any class that implements FilenameFilter, using it to determine (even at runtime) how the list () method behaves. The purpose of the callback is to provide greater flexibility in the behavior of the code.
By Dirfilter, we see that although an "interface" contains only a series of methods, it is not limited to writing only those methods (but at least it must provide a definition of all the methods within an interface). In this case, the Dirfilter Builder is also created.
The Accept () method must accept a file object that indicates the directory used to find a particular file, and a string that contains the name of the file to be looked for. You can decide to use or ignore one of these two parameters, but sometimes at least the file name is used. Remember that the list () method prepares to invoke accept () for each filename in the directory object, verifying which one should be included--specifically the "Boolean" result returned by accept ().
To determine that we are working with only the filename, which does not contain path information, you must take a string object and create a file object outside of it. The GetName () is then invoked to remove all path information (in a platform-independent manner). Subsequently, accept () uses the IndexOf () method of the string class to check for the existence of the search string "AFN" inside the file name. If a AFN is found within a string, the return value is the index of the starting point of the AFN, but if not found, the return value is-1. Note This is just a simple string search example, not using the common expression "wildcard" scheme, such as "fo?". B?r* "; This scheme is more difficult to achieve.
The list () method returns an array. You can query the length of the array, and then iterate through it, selecting the elements of the array. Compared to C and C + +, this method of facilitating the travel of arrays within and outside of the approach is undoubtedly a significant improvement.

1. Anonymous inner class
The following example overrides an anonymous inner class (already described in chapter 7th) to be ideal. First, you create a filter () method that returns a handle to the FilenameFilter:

//: Dirlist2.java//Uses Java 1.1 anonymous inner import classes; public class DirList2 {public static filenamefilter filter (final String AFN) {//creation of anonymous inner CL
      Ass:return New FilenameFilter () {String fn = AFN;
        Public Boolean Accept (File dir, String N) {//Strip path information:string f = new File (n). GetName ();
      Return F.indexof (FN)!=-1; }
    }; 
      End of anonymous inner class} public static void Main (string[] args) {try {File path = new File (".");
      String[] list;
      if (Args.length = = 0) List = Path.list ();
      else List = Path.list (filter (args[0]));
    for (int i = 0; i < list.length i++) System.out.println (list[i));
    catch (Exception e) {e.printstacktrace (); }
  }
} ///:~


Note that the independent variable of the filter () must be final. This is required by the anonymous inner class to enable it to use an object from outside its own scope.
The reason to think this is better is that the FilenameFilter class is now tightly integrated with DIRLIST2. However, we can take further steps to define an anonymous inner class as a parameter of list () to make it more streamlined. As shown below:

: Dirlist3.java
//Building the anonymous inner class "In-place"
import java.io.*;

public class DirList3 {public
  static void Main (final string[] args) {
    try {
      File path = new File (".");
      string[] list;
      if (Args.length = = 0)
        list = Path.list ();
      else 
        list = path.list (
          new FilenameFilter () {public
            Boolean 
            accept (File dir, String N) {
              String f = new File (n). GetName ();
              Return F.indexof (Args[0])!=-1;
            }
          });
      for (int i = 0; i < list.length i++)
        System.out.println (list[i);
    } catch (Exception e) {
      E.printstacktrace ();}}
///:~

The


Main () is now a final argument because the anonymous inner class directly uses Args[0.
This shows how to quickly create a streamlined class with anonymous inner classes to solve some complex problems. Because everything in Java is related to a class, it is undoubtedly a fairly useful coding technique. One advantage of it is to isolate specific problems in one place and solve them uniformly. But on the other hand, this generated code is not very easy to read, so you must use caution.

2. The sequential directory list
often requires file names to be provided in a sorted way. Since Java 1.0 and Java 1.1 Do not provide sort support (from Java 1.2), you must add this capability directly to your program with the Sortvector created in chapter 8th. As follows:
 

: Sorteddirlist.java//Displays sorted directory listing import java.io.*;

Import c08.*;
  public class Sorteddirlist {private File path;
  Private string[] list;
    Public sorteddirlist (Final String afn) {path = new File (".");
    if (AFN = = null) List = Path.list (); else list = Path.list (new FilenameFilter () {public Boolean accept (File dir, Str
              ing N) {String f = new File (n). GetName ();
            Return F.indexof (AFN)!=-1;
    }
          });
  Sort ();
  } void Print () {for (int i = 0; i < list.length i++) System.out.println (list[i));
    private void Sort () {Strsortvector SV = new Strsortvector ();
    for (int i = 0; i < list.length i++) sv.addelement (list[i)); The "A" is pulled from//the Strsortvector the "list is sorted:for" (int i = 0; i < List.le Ngth;
  i++) List[i] = Sv.elementat (i); }//Test it:public staticvoid Main (string[] args) {sorteddirlist sd;
    if (Args.length = = 0) sd = new sorteddirlist (null);
    else SD = new Sorteddirlist (args[0]);
  Sd.print (); }
} ///:~


A little further improvement was made here. Instead of creating a local variable that creates the path (path) and list as main (), they become members of the class so that their values are easily accessible during the object's "live" period. In fact, main () is now just a way to test the class. As you can see, once the list is created, the Class builder automatically starts sorting the list.
This sort does not require case sensitivity, so you end up with a list of all the words that begin with a capital letter, followed by a list of all lowercase letters. However, we notice that in a set of filenames that begin with the same letter, uppercase letters are in the front-which is still an unqualified behavior for standard sorting. Java 1.2 has successfully solved this problem.

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.