英文:
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 < 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);
}
}
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<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);
}}));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论