【问题标题】:I'm trying to filter the files by date我正在尝试按日期过滤文件
【发布时间】:2019-04-19 12:20:59
【问题描述】:

我正在尝试按日期过滤文件并读取每个文件。我有一个读取每个文件名的 find() 方法,它返回一个以数组中“B”开头的文件。第二种方法filesort(),它将返回从find()方法发送的文件名中的所有文件日期。在主要方法中,我想在我给出的特定日期之前读取文件。如果所有文件的日期相同,则读取所有文件。但是,从文件中,其中一个文件具有不同的日期,它会引发错误。

public static String[] find(String rootPath){

   File root = new File(rootPath);
   // Filter files whose name start with "B"
   FilenameFilter beginswithm = new FilenameFilter() {
       public boolean accept(File directory, String filename) {
           return filename.startsWith("B");
       }
   };
   // array to store filtered file names
   String[] files = root.list(beginswithm);
   String[] no = { "nofile" };
   if (files == null) {
       return no;
   }  
   return files;

}

   public String filesort() throws ParseException {
   String path = "C:";
   String [] filesList = find(path);
   for (String file : filesList) {
       File st = new File(file);
       String name=st.getName();
       name= name.replaceAll("\\D+", "");
       String Datename = name.substring(0, 8);
       DateFormat formatter = new SimpleDateFormat("yyyymmdd");
       Date date = (Date)formatter.parse(Datename);
       SimpleDateFormat newFormat = new SimpleDateFormat("mm/dd/yyyy");
       String finalString = newFormat.format(date);
       return finalString;
   }
   return "error";

}

           public static void main(String[] args){
   String path = "C:";
   String [] filesList = find(path);
       for (String file : filesList) {
   if(filesort().equals("04/17/2019"))//to read all files that has 04/17/2018
    {
   reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(path + "//" +file))));
       String content;
       while ((content = reader.readLine()) != null) {
           System.out.println(content);
           }  
   }
       else if (!filesort().equals("04/17/2019")||filesort()==null ) {
           System.out.println("incorect date");
       }

}

this are the files I'm trying to read
 BProce.Arr.20190416.server10.gz
 BProce.Arr.20190417..ball10.gz
 BProce.Arr.20190417.ball23.gz

因为第一个文件是 04/16/2019,它会抛出错误的日期。如果其中 3 个具有 04/17/2019,它将毫无问题地读取。 但现在我只想读取日期为 04/17/2019 的文件

【问题讨论】:

  • 我非常建议你不要使用SimpleDateFormatDate。前者是出了名的麻烦,后者设计也很糟糕,幸运的是两者都已经过时了。您应该使用LocalDateDateTimeFormatter,两者都来自jege.time, the modern Java date and time API
  • 能否请您:(1)更清楚您的问题?在 Java 行话中 throw 意味着抛出异常,但我怀疑这是否是你的问题?或者你的意思是抛出不正确的日期? (2) 以更易读的方式缩进和格式化您的代码?使用编辑字段上方的{} 按钮确保代码被格式化为问题中的代码。谢谢。老实说:即使在 3 个答案之后,我仍然相信我可以贡献一些有用的东西,但我不想像现在这样在你的代码中挣扎。

标签: java file date gzip


【解决方案1】:

如果我们从另一个角度来看问题,似乎很容易实现你想要的。我将给出基本逻辑。

  1. 从目录中读取文件名。 here 是如何做到这一点的示例
  2. 将名称存储在 ArrayList 中
  3. 使用集合对 ArrayList 进行排序following 链接对您有帮助
  4. 现在您已经对目录的文件名进行了排序,只要您需要访问,只需访问 ArrayList 元素并使用它访问真实文件

Happy Coding,如果还有问题请告诉我

【讨论】:

    【解决方案2】:

    要查找名称以“B”开头并包含特定日期的文件,只需按照此过程。

    您可以使用此代码和File 类查找所有文件。

    public File[] find(String path) {
        File dir = new File(path);
        File[] listOfFiles = null;
        if (dir.isDirectory()) {
             listOfFiles = dir.listFiles();
        }
    
        return fileList;
    }
    

    从这个文件列表中你可以得到文件名然后检查这个文件名以'B'开头并且 检查它是否包含特定日期。字符串对象有startsWith() 方法。您不需要将日期字符串更改为 Date 对象。只需检查文件名是否包含日期字符串。

    【讨论】:

      【解决方案3】:

      永远不要使用糟糕的DateDateFormatSimpleDateFormat 类。仅使用 java.time 类。

      Answer by Rishoban 看起来正确。再加上这个关于解析日期的讨论。

      通过调用File::isFile 询问每个File 对象是否代表一个文件和一个目录。调用File::getName 以生成带有文件名文本的String。然后使用String::startsWithString::substring分析文件名。拉出可能日期的文本。通过尝试将文本解析为LocalDate 进行验证。使用格式模式定义 DateTimeFormatter 以匹配您的预期输入。

      LocalDate targetDate = LocalDate.of( 2019 , Month.APRIL , 17 ) ;
      DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu" ) ;
      int lengthOfExpectedDateInput = 10 ; // "01/23/2019" is 10 characters long.
      String fileName = file.getName() ;
      if( file.isFile() && fileName.startsWith( "B" ) ) {
          String possibleDateInput = fileName.substring( 1 , 1 + lengthOfExpectedDateInput ) ;  // Annoying zero-based index counting where 1 means the 2nd position. 
          try {
              LocalDate ld = LocalDate.parse( possibleDateInput , f ) ;  // Parse string as a `LocalDate` object. If input fails to match formatting pattern, a `DateTimeParseException` is thrown.
              if( ld.isEqual( targetDate ) ) {
                  // Handle a valid file with expected file name.
                  …
              }
          } catch ( DateTimeParseException e ) {
              // Handle unexpected file name.
              …
          }
      }
      

      顺便说一下,让这些文件名的发布者了解ISO 8601 标准。日期应采用 YYYY-MM-DD 格式。

      您的问题确实与许多其他问题重复。发帖前先搜索 Stack Overflow。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-25
        • 2022-11-07
        • 2011-12-04
        • 1970-01-01
        • 2022-06-15
        • 2019-11-07
        相关资源
        最近更新 更多