使用JSP的文件夹中的特定扩展名的列表文件
问题描述:
<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。任何人都可以告诉我如何去做这件事?使用JSP的文件夹中的特定扩展名的列表文件
答
你需要一个FilenameFilter并实现它的方法accept在这种方式,你只接受文件巫婆有你需要的扩展名。
这里是一个示例代码
new File("").list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
});
请注意,此代码是不区分大小写,所以用.TXT
结尾的文件会被过滤掉。您可能需要提取扩展名,然后使用equalsIgnoreCase进行比较。在致电endsWith之前,您也可以拨打LowerCasename
。
答
<%@ page import="java.io.*" %>
<%
String file = application.getRealPath("/results");
File f = new File(file);
String [] fileNames = f.list();
int i = 0;
String fname=null;
File [] fileObjects= f.listFiles();
BufferedReader readReport;
int num=0;
{
%>
<table name="reports">
<th width=12.5% align="center" bgcolor="gray">Execution ID</th>
<th width=12.5% align="center" bgcolor="gray">Parent suite name</th>
<th width=12.5% align="center" bgcolor="gray">Execution date</th>
<th width=12.5% align="center" bgcolor="gray">Total execution time(seconds)</th>
<th width=12.5% align="center" bgcolor="gray">Pass</th>
<th width=12.5% align="center" bgcolor="gray">Fail</th>
<th width=12.5% align="center" bgcolor="gray">Skip</th>
<th width=12.5% align="center" bgcolor="gray">Summary</th>
<%
}
for (i=0; i < fileObjects.length; i++)
{
if(!fileObjects[i].isDirectory())
{
fname = "../results/"+fileNames[i];
if(fname.endsWith(".html"))
{
String Name = fileNames[i].substring(0, fileNames[i].indexOf('.'));
{
%>
<tr bgcolor="lightgray">
<td width=12.5% align="center">
<%=Name%>
</td>
<td width=12.5% align="center">
</td>
<td width=12.5% align="center">
</td>
<td width=12.5% align="center">
</td>
<td width=12.5% align="center">
</td>
<td width=12.5% align="center">
</td>
<td width=12.5% align="center">
</td>
<td width=12.5% align="center">
<a HREF="<%= fname %>" target="loadReport"><button>View</button></a>
</td>
</tr>
<%
}
}
}
}
{%></table> <%}
%>
+0
使用的endsWith()fnction :) – 2017-03-08 10:08:29
+0
这是不是比要求更多的代码?表格与其余部分有什么关系?另外,在另一个答案中已经提出使用'endsWith'! – 2017-03-08 10:39:47
可能重复:http://stackoverflow.com/questions/5751335/using-file-listfiles-with-filenameextensionfilter – vish213 2013-05-02 19:13:54