问题描述
<h1>Directories</h1>
<ul>
<%
String root="c:/Repository/WebApplication/mydocs/javadoc/";
java.io.File file;
java.io.File dir = new java.io.File(root);
String[] list = dir.list();
if (list.length > 0) {
for (int i = 0; i < list.length; i++) {
file = new java.io.File(root + list[i]);
if (file.isDirectory()) {
%>
<li><a href="javadoc/<%=list[i]%>" target="_top"><%=list[i]%></a><br>
<%
}
}
}
%>
</ul>
上面的代码有效,即它列出了所有文件,我只想列出特定扩展名的文件,例如.txt.谁能告诉我该怎么做?
The above code works, i.e it lists all the files, I want to list only files of specific extensions such as .txt. Can anyone pl tell me how to go about this?
推荐答案
您需要 FilenameFilter 并通过接受,使您仅接受具有所需扩展名的文件.
You need a FilenameFilter and implements it method accept in such a way that you accept only file witch have the extension you need.
这是示例代码
new File("").list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
});
请注意,此代码不区分大小写,因此将滤除以.TXT
结尾的文件.您可能要提取扩展名,然后使用 equalsIgnoreCase 进行比较.或者,您可以 LowerCase name
,然后调用 endsWith .
Note that this code is not case sensitive, so files ending with .TXT
will be filtered out. You may want to extract the extension and then use equalsIgnoreCase to compare it. Alternatively you can LowerCase name
before calling endsWith.
这篇关于使用JSP列出文件夹中特定扩展名的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!