2013-07-23 86 views
-1

在我的Java程序中,我处理一定数量的文件。 这些文件被命名为这样: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等? (如下:a生动的例子)

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 

我希望我是清楚的

+2

答案很清楚。您所需要的只是编写代码,它首先读取来自特定单元(例如128)的所有txt,然后是来自单元129的所有文件,等等。除非您显示您尝试过的内容,否则我们无法为您提供帮助。 – Leri

+0

@PLB,在[这篇文章](http://stackoverflow.com/questions/17772716/java-string-comparing-among-many-txt-files)有我用于这个程序的代码:) – alessandrob

回答

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 
    } 
}); 
0

嗯,你可以为了得到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 
} 
0

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

cellnumber_yyyymmdd_hhmmss 

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

否则,您必须编写自定义比较器(如@RiaD写入),但由于必须解析日期以便稍后/更早决定,因此这不是微不足道的。