How to read file passing part of the name in Java

7

Example.:

The name of my file would be 001nome.txt , this file will have a variable action on the name depending on the entity, ie an hour it can be 001nome.txt at another time it can be 999nome.txt .

Doubt.:

How can I move to Java open this file regardless of this variation in the name?

Note: In php I do so *nome.txt it returns me the file that has the end nome.txt independent of the beginning of its name.     

asked by anonymous 28.02.2014 / 20:11

3 answers

4

Using the Java API

Create a File object pointing to the directory and it iterates over the files it checks to see if they have the desired pattern.

The implementation of the iteration can be done using the

28.02.2014 / 20:23
1

This method solved a similar problem I had.

FileFilter filter = new FileFilter() {  
    public boolean accept(File file) {  
        return file.getName().endsWith("name.txt");  
    }  
};

File dir = new File("/caminho/do/seu/diretorio");  
File[] files = dir.listFiles(filter);  

.endsWith("name.txt"); can solve some of your problem since it takes all files that end with the specified String.

    
28.02.2014 / 20:50
0

Use an expression close to this. This expression allows something like 20140512_0000_xxxxxxxxxx.xml.gz being yyyymmdd_hhmm_client.xml.gz

Pass this expression to getFilter() then use getListFiles()

This RegexFileFilter class is the apache commons io project

"^[\d]{8}_[\d]{4}_[\w]+\.xml\.gz$"

 private List<File> getListFiles() {
    List<File> list = Arrays.asList(this.sourceDirectory.listFiles(getFilter()));
    Collections.sort(list);
    return list;
  }    

  private FileFilter getFilter() {
    return new RegexFileFilter(FILE_FILTER);
  }
    
28.02.2014 / 20:25