如何使用模式/过滤器从目录获取文件 [英] How to get file from directory with pattern/filter

查看:147
本文介绍了如何使用模式/过滤器从目录获取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从PDF文件目录中获取文件。我有一个问题,我没有一个字段来连接所有的数据来找到该文件。



这里有一个例子:



文件名:

  Comp_20120619_170310_2_632128_FC_A_8_23903.pdf 

文件名生成:

  Comp_20120619 _-- ------_ 2_632128_FC_A_8_23903.pdf 

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



我正在尝试使用文件

解决方案

你可以定义一个 FilenameFilter 与文件名匹配,如果文件名与您的文件名匹配,则返回true寻找。

 文件dir =新文件(/ path / to / pdfs); 
文件[] 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);
}
});

listFiles()方法返回一个数组的File对象。这是有道理的,因为可能有多个文件与模式匹配(至少在理论上至少不一定在系统中)。



我已经使用了正则表达式匹配文件名,使用 [^ _] * 匹配您不确定的部分。但是,如果文件名匹配,您可以使用任何返回布尔值的函数。例如,您可以使用 startsWith endsWith 而不是正则表达式。


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.

解决方案

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.

这篇关于如何使用模式/过滤器从目录获取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆