How to get file from directory with pattern/filter

折月煮酒 提交于 2019-12-19 17:15:04

问题


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.


回答1:


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.




回答2:


What's your problem with list() ?

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



回答3:


It's possible tu use a 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)



回答4:


Hope it 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"));          
             }
        };
    }


来源:https://stackoverflow.com/questions/13515150/how-to-get-file-from-directory-with-pattern-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!