Java使用filename中的动态子字符串查找所有文件

时间:2014-07-23 13:52:53

标签: java

我试图编写一个Java代码,找到包含文件名中确定的子字符串的所有文件。该子字符串是程序的动态输入,因此它存储在字符串变量中,在此处命名为" log3":

File fl = new File(dir); //fl is the directory in which look for files
File[] matchingFiles = fl.listFiles(new FileFilter() {
    public boolean accept(File x) {
         return (x.getName().contains(log3));
    }
});

问题是当我编译代码时出现此错误:

 local variable log3 is accessed from within inner class; needs  to be
 declared final
                 return (x.getName().contains(log3);
                                                             ^

4 个答案:

答案 0 :(得分:0)

属于外部类的局部变量在内部类中是不可见的,除非它被声明为final。

示例:

private class Foo {

  private int v1; //Visible from the inner class because it is an attribute.

  public void bar() {

    int v2 = true; //Not visible from the inner class
    final boolean v3 //Visible from the inner class

    new InnerClass() {

      public void overridenMethod() {
        //Here, you can use v1 and v3 but not v2

      }
    }
  }
}

您的变量log3必须声明为final。

答案 1 :(得分:0)

我知道您不能将log3声明为最终版,因为它会在您的程序范围内更改。为了解决这个问题,你可以这样做:

final String nameSubstring = log3;
File fl = new File(dir); //fl is the directory in which look for files
File[] matchingFiles = fl.listFiles(new FileFilter() {
    public boolean accept(File x) {
         return (x.getName().contains(nameSubstring));
    }
});

答案 2 :(得分:0)

我今天遇到了完全相同的问题,并通过错误消息弄明白了。它在错误消息中清楚地说明:只需在您的外部类中声明log3final

答案 3 :(得分:0)

尝试实现自己的FileFilter,因此您不必将该字段设为最终:

public class FilesTest {

 public static void main(String[] args) {
     new FilesTest();
 }

 public FilesTest() {

     File fl = new File("D:/");
     File[] matchingFiles = fl.listFiles(new CustomFileFilter("A."));
     for (File file : matchingFiles) {
          System.out.println(file.getAbsolutePath());
     }
 }

 class CustomFileFilter implements FileFilter {

     private String pattern;

     public CustomFileFilter(String pattern) {
         this.pattern = pattern;
     }

     public boolean accept(File x) {
         return (x.getName().contains(pattern));
     }
 }
}