How to get a file from a template / filter directory

I need to get a file from a PDF file directory. I have a problem that I do not have a field to define all the data to find the file.

Here is an example:

File name:

Comp_20120619_170310_2_632128_FC_A_8_23903.pdf 

Generate file name:

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

I do not have the "--------" field to make the file name COMPLETE.

I try with File.list , but I can not find the correct file.

+7
source share
4 answers

You can define a FilenameFilter to match with file names and return true if the file name matches what you are 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 can be more than one file that matches the pattern (theoretically, at least, although not necessarily on your system).

I used a regular expression to match a file name, using [^_]* to match a section you are not sure about. However, you can use any function that returns a boolean if the file name matches. For example, you can use startsWith and endsWith instead of the usual expression.

+16
source

What is the problem with list() ?

 File folder = new File("path/to/pdffilefolder"); String[] allFilesInThatFolder = folder.list(); // contains only files, no folders. 
+1
source

You can use the file WildcardFileFilter (org.apache.commons.io.filefilter)

The code looks simple:

 FilenameFilter filenameFilter = new WildcardFileFilter("Comp_20120619_*_2_632128_FC_A_8_23903.pdf"); String[] pdfFileNames = yourDir.list(filenameFilter); if(pdfFileNames != null ) { for (String pdfName : pdfFileNames) 
+1
source

Hope this works.

 String[] pdfFiles= yourDir.listFiles(getFileNameFilterMachingWithFileName("Comp_20120619_")); private FilenameFilter getFileNameFilterMachingWithFileName(final String fileNameStart) { return new FilenameFilter() { @Override public boolean accept(File dir, String name) { return (name.toUpperCase().startsWith(fileNameStart.toUpperCase()) && name.toUpperCase().endsWith(".PDF")); } }; } 
+1
source

All Articles