Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get file from directory with pattern/filter

I have to get a file from a PDF files directory. I have problem that I haven't a field to concant all data to find the file.

Here's an example:

File name:

Comp_20120619_170310_2_632128_FC_A_8_23903.pdf

File name generate:

Comp_20120619_--------_2_632128_FC_A_8_23903.pdf

I dont' have the field "--------" to make file COMPLETE name.

I'm trying with File.list but I cannot find the correct file.

like image 847
backLF Avatar asked Nov 22 '12 14:11

backLF


People also ask

How to match File name pattern in Java?

Once we obtain an interface to the filesystem by invoking the getDefault() method, we use the getPathMatcher() method from the FileSystem class. This is where we apply glob patterns on the individual file paths within rootDir. In our case, we can use the resulting PathMatcher to get an ArrayList of matching filenames.

How to use FilenameFilter in Java?

In Java, we can use FilenameFilter class. It tests if a specified file should be included in a file list. To use FilenameFilter, override the accept(dir, name) method that contains the logic to check if the file has to be included in the filtered list.

How do I filter files with OS Listdir?

How to Filter and List Files According to Their Names in Python? To filter and list the files according to their names, we need to use “fnmatch. fnmatch()” and “os. listdir()” functions with name filtering regex patterns.


1 Answers

You can define a FilenameFilter to match against the filenames, and return true if the filename matches what you're looking for.

    File dir = new File("/path/to/pdfs");
    File[] files = dir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.matches("Comp_20120619_[^_]*_2_632128_FC_A_8_23903.pdf");
        }
    });

The listFiles() method returns an array of File objects. This makes sense, because there might be more than one file that matches the pattern (in theory at least, albeit not necessarily in your system).

I've used a regular expression to match the filename, using [^_]* to match the section you're not sure about. However, you can use any function that will return a boolean if the filename matches. For example, you could use startsWith and endsWith instead of a regular expression.

like image 105
Martin Ellis Avatar answered Sep 25 '22 15:09

Martin Ellis