【问题标题】:Java - Read specific files in specific order from a folder [closed]Java - 从文件夹中按特定顺序读取特定文件[关闭]
【发布时间】:2013-07-23 09:36:12
【问题描述】:

在我的 Java 程序中,我处理了一定数量的文件。 这些文件以这种方式命名:

thu 21 mar 2013_01.55.22_128.txt
thu 21 mar 2013_01.55.22_129.txt
thu 21 mar 2013_01.55.22_130.txt
....
sat 23 mar 2013_01.45.55_128.txt
sat 23 mar 2013_01.45.55_129.txt
sat 23 mar 2013_01.45.55_130.txt

其中最后三个数字是单元格编号。 考虑到我已经按日期顺序阅读了来自同一单元格的文件。 考虑到所有文件都在同一个文件夹中。 还要考虑这个问题,但对于单个单元格,在This Post

上已正确解决

我现在的问题是:如何首先读取来自特定单元格(例如 128)的所有 txt,然后读取来自单元格 129 的所有文件等等? (下图示例)

thu 21 mar 2013_01.55.22_128.txt
sat 23 mar 2013_01.45.55_128.txt
...
thu 21 mar 2013_01.55.22_129.txt
sat 23 mar 2013_01.45.55_129.txt
...
thu 21 mar 2013_01.55.22_130.txt
sat 23 mar 2013_01.45.55_130.txt

希望我清楚

【问题讨论】:

  • 答案很明确。您只需编写代码,首先读取来自特定单元格(例如 128)的所有 txt,然后读取来自单元格 129 的所有文件,依此类推。除非您展示您的尝试,否则我们无法为您提供帮助。
  • @PLB,在This Post 中有我用于这个程序的代码 :)

标签: java


【解决方案1】:

您可以使用listFiles() 将目录中的所有文件放入数组中,然后使用自定义比较器对其进行排序。

File[] files = dir.istFiles();
Array.sort(files, new Comparator<File> {
    @Override
    public int compare(File lhs, File rhs) {
        //return -1 if lhs should go before
        //0 if it doesn't matter
        //1 if rhs should go after
    }
});

【讨论】:

    【解决方案2】:

    好吧,您可以读取文件夹以获取 File 对象(或者可能只是文件名)。 然后解析文件名,提取单元格并将文件放入以单元格为键的映射中。

    一些伪代码:

    Map<String, List<File>> filesPerCell = new LinkedHashMap<String, List<File>>();
    
    File[] files = folder.listFiles();
    
    for( File file : files ) {
      String filename = file.getName();
      String cell = ... ; //extract from filename
      List<File> l = filesPerCell.get( cell );
    
      //create new list if l is null
    
      l.add( file ); 
    }
    
    for( List<File> cellList : filesPerCell.values() ) {
      //do whatever you want with the files for that cell
    }
    

    【讨论】:

      【解决方案3】:

      您的文件名将按单元格编号排序,在单元格内按日期/时间排序。如果你的文件名是这样的,你可以最容易地做到这一点:

      cellnumber_yyyymmdd_hhmmss
      

      其中 cellnumber 在所有情况下都是相同的位数。

      否则,您必须编写一个自定义比较器(如@RiaD 所写),但这并非易事,因为必须解析日期,以便稍后/更早做出决定。

      【讨论】:

        猜你喜欢
        • 2020-02-10
        • 2016-03-05
        • 2017-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-23
        相关资源
        最近更新 更多