列出一个目录中的文件,根据用户在Java中提供的名称列表。

huangapple go评论61阅读模式
英文:

List the files in a directory based on a list of names provided by user in java

问题

目前,我可以使用以下函数获取文件名列表。

public class HelloWorld {

    public static void main(String[] args) {

        List<String> s = new ArrayList<>();
        s.add("AulaIternational.pdf");
        s.add("Spanish Essentials For Dummies.pdf");
        List<File> flist = new ArrayList<>();

        for (String str : s) {
            File newFile = new File("C:\\Users\\Spanish Training\\" + str);
            if (newFile.exists()) {
                flist.add(newFile);
            }
        }
        System.out.println(flist);
    }
}

输出结果: "C:\Users\Spanish Training\AulaIternational.pdf, C:\Users\Spanish Training\Spanish Essentials For Dummies.pdf"

我的问题:是否可以使用 file.listfile(Filter) 函数来简化相同的操作,还是我正在做正确的事情?

英文:

Currently, I am able to obtain the list of names of files using the following function.

public class HelloWorld {

    public static void main(String[] args) {

        List &lt; String &gt; s = new ArrayList &lt; &gt; ();
        s.add(&quot;AulaIternational.pdf&quot;);
        s.add(&quot;Spanish Essentials For Dummies.pdf&quot;);
        List &lt; File &gt; flist = new ArrayList &lt; &gt; ();

        for (String str: s) {
            File newFile = new File(&quot;C:\\Users\\Spanish Training\\&quot; + str);
            if (newFile.exists()) {
                flist.add(newFile);
            }
        }
        System.out.println(flist);
    }
}

Output : "C:\Users\Spanish Training\AulaIternational.pdf, C:\Users\Spanish Training\Spanish Essentials For Dummies.pdf"

My Question: Can the same thing be simplified using file.listfile(Filter) or I am doing the correct thing?

答案1

得分: 1

不会过于简化,但看起来更易读。

List<File> flist = Arrays.asList(new File("C:\\Users\\Spanish Training\\").listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return s.contains(name);
    }}));
英文:

Will not simplify too much, but looks bit more readable

List&lt;File&gt; flist = Arrays.asList(new File(&quot;C:\\Users\\Spanish Training\\&quot;).listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
	return s.contains(name);
}}));

huangapple
  • 本文由 发表于 2020年9月14日 17:38:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63881800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定