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

后端 未结 2 1016
夕颜
夕颜 2021-01-24 21:02

I\'m trying to find a file based on the first 8 numbers i pull from an excel sheet for each iteration. Whenever I use the code below I get the error message \"Local variable Cas

相关标签:
2条回答
  • 2021-01-24 21:35

    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);
        } 
    };
    
    0 讨论(0)
  • 2021-01-24 21:47

    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);
    
    0 讨论(0)
提交回复
热议问题