7

我必须从 PDF 文件目录中获取文件。我有一个问题,我没有一个字段来合并所有数据来查找文件。

这是一个例子:

文件名:

Comp_20120619_170310_2_632128_FC_A_8_23903.pdf

文件名生成:

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

我没有"--------"使文件完整名称的字段。

我正在尝试,File.list但找不到正确的文件。

4

4 回答 4

17

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.

于 2012-11-22T14:54:04.163 回答
1

你有什么问题list()

File folder = new File("path/to/pdffilefolder");
String[] allFilesInThatFolder = folder.list();
// contains only files, no folders.
于 2012-11-22T14:52:43.357 回答
1

希望它有效..

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"));          
             }
        };
    }
于 2017-11-07T06:13:00.813 回答
1

您可以使用 WildcardFileFilter (org.apache.commons.io.filefilter)

代码看起来很简单:

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)
于 2017-01-13T09:51:34.403 回答