How to find a file using a variable for 'Startswith' in Java

扶醉桌前 提交于 2019-12-02 04:10:52

Here:

FilenameFilter filter = new FilenameFilter() {
    public boolean accept (File dir, String name) { 
        return name.startsWith(caseID);
    } 
};

You cannot use a mutable variable in the definition of an inner local class. That's why you receive the error compiler.

Create a temporary variable and assign the value of caseID there, use this variable in your inner local class:

final String localCaseID = caseID;
FilenameFilter filter = new FilenameFilter() {
    public boolean accept (File dir, String name) { 
        return name.startsWith(localCaseID);
    } 
};

You can use inner class instead of anonymous one. Define it like:

   private static class CaseIDFilenameFilter implements FilenameFilter {
       private final String caseID;

       private CaseIDFilenameFilter(String caseID) {
           this.caseID = caseID;
       }

       @Override
       public boolean accept(File dir, String name) {
           return name.startsWith(caseID);
       }
}

And then use it in your code like:

FilenameFilter filter = new CaseIDFilenameFilter(str);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!