日期:2014-05-18  浏览次数:20674 次

用JSP如何列出文件目录....
比如说。。。我在D盘放上一个文件。。。然后在jsp页面里如何列出该文件。。并提供下载连接。。。

------解决方案--------------------


import java.io.*;

public class FindDirectories
{
public static void main(String[] args)
{
// if no arguments provided, start at the parent directory
FindDirectories.FindFiles(new String[]{ "c:\\ "});


}
public static void FindFiles(String[]str)
{
if (str.length ==0) str = new String[]{ ".. "};
try
{
File pathName = new File(str[0]);
if (pathName.exists() )
{
String[] fileNames = pathName.list();

// enumerate all files in the directory
for (int i = 0; i < fileNames.length; i++)
{
File f = new File(pathName.getPath(), fileNames[i]);

// if the file is again a directory, call the main method recursively
if (f.isDirectory())
{
// System.out.println(f.getCanonicalPath());
FindFiles(new String[]{f.getCanonicalPath()});
}
else
{
System.out.println(f.getCanonicalPath());
}
}
}
}
catch(IOException e)
{

e.printStackTrace();
}
}
}



------解决方案--------------------
String path=application.getRealPath(this.getServletName());
path=path.substring(0,path.lastIndexOf( "\\ "));
path=path+ "\\download ";
//String temppath=request.getContextPath();
//temppath=temppath+ "/download ";
//out.print(temppath);
//response.setContentType( "application/x-download ");//设置为下载application/x-download
String realFileName;
File download = new File(path);
String[] FileNames = download.list();
for(int i=0;i <FileNames.length;i++)
{
//realFileName=new String(FileNames[i].getBytes( "iso-8859-1 "), "gb2312 ");
out.print( " <li> <a href=rDownLoad.jsp?filename= "+FileNames[i]+ "> "+FileNames[i]+ " </a> </li> <br> <br> ");
}


然后在rDownLoad.jsp里用一个SmartUpload组件来实现下载:
String filename=new String(request.getParameter( "filename ").getBytes( "ISO-8859-1 "), "GB2312 ");
SmartUpload su = new SmartUpload();
su.initialize(pageContext);
su.setContentDisposition(null);
su.downloadFile( "/download/ "+filename);
------解决方案--------------------
mark