我有一个名为output.txt 的文本文件,它将在D:/MPI 中生成。我必须下载这个文件,但下载的文件完全是空白的,没有任何内容。我想下载位于 D:/MPI 文件夹中的文件 output.txt。这是我的 JSP 代码
<%
String filePath = "D://MPI//output.txt";
String fileName = "outputs";
FileInputStream fileToDownload = new FileInputStream(filePath);
ServletOutputStream output = response.getOutputStream();
response.setContentType("text/plain; charset=utf-8");
response.setHeader("Content-Disposition","attachment; filename="+fileName);
response.setContentLength(fileToDownload.available());
int c;
while((c=fileToDownload.read()) != -1){
out.write(c);
}
output.flush();
output.close();
fileToDownload.close();
%>
请指导我
最佳答案
您正在开发一个 Web 应用程序,文件将从 Web 服务器提供。因此,请尝试使路径相对于应用程序的上下文,而不是使用绝对路径。
尝试使用ServletContext#getRealPath()返回包含给定虚拟路径的真实路径的字符串的方法。
将 output.txt
文件放入项目的 war/webapp 文件夹中,然后尝试以下代码:
String filePath = request.getServletContext().getRealPath("output.txt");
<小时/>
注意:始终尽量避免使用 Scriplet,而使用 JSTL 。在本例中,将此代码从 JSP 移至 Servlet 中。将 JSP 视为 UI,并始终将业务和数据库逻辑保留在 Servlet 中。
关于java - 文件正在下载但里面没有任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24096768/