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

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

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

问题

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

  1. public class HelloWorld {
  2. public static void main(String[] args) {
  3. List<String> s = new ArrayList<>();
  4. s.add("AulaIternational.pdf");
  5. s.add("Spanish Essentials For Dummies.pdf");
  6. List<File> flist = new ArrayList<>();
  7. for (String str : s) {
  8. File newFile = new File("C:\\Users\\Spanish Training\\" + str);
  9. if (newFile.exists()) {
  10. flist.add(newFile);
  11. }
  12. }
  13. System.out.println(flist);
  14. }
  15. }

输出结果: "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.

  1. public class HelloWorld {
  2. public static void main(String[] args) {
  3. List &lt; String &gt; s = new ArrayList &lt; &gt; ();
  4. s.add(&quot;AulaIternational.pdf&quot;);
  5. s.add(&quot;Spanish Essentials For Dummies.pdf&quot;);
  6. List &lt; File &gt; flist = new ArrayList &lt; &gt; ();
  7. for (String str: s) {
  8. File newFile = new File(&quot;C:\\Users\\Spanish Training\\&quot; + str);
  9. if (newFile.exists()) {
  10. flist.add(newFile);
  11. }
  12. }
  13. System.out.println(flist);
  14. }
  15. }

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

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

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

Will not simplify too much, but looks bit more readable

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

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:

确定