java.io.FileNotFoundException(没有此类文件或目录)-下载文件

时间:2020-10-07 19:19:42

标签: java linux

我在Linux上托管了Web应用程序,其中包含用于上载.rar文件的页面和用于下载该文件的页面。的上传功能正常工作,文件成功上传到服务器,但是下载后出现以下异常:

 [servelt.scriptdownloadservelt] in context with path [/OSS-CPE-Tracker] threw exception
  java.io.FileNotFoundException: \usr\local\apache-tomcat-8.5.31\OSS-CPE-Tracker\Zaky\QCAM.rar (No such file or directory)

我使用以下功能进行上传:

String destDir = "/usr/local/apache-tomcat-8.5.31/OSS-CPE-Tracker/Zaky";
            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    if(name.equalsIgnoreCase("QCAM.rar")) {
                                                
                    File destFile = new File(destDir, "QCAM.rar");
                    if (destFile.exists()) {
                        destFile.delete();
                    }
                    item.write(new File("/usr/local/apache-tomcat-8.5.31/OSS-CPE-Tracker/Zaky" + File.separator + name));
                    request.setAttribute("gurumessage", "File Uploaded Successfully");

                }else {
                    request.setAttribute("gurumessage", "Kindly use the agreed name");

                }

这里出现我遇到的问题和上述异常的下载功能:

response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String gurufile = "QCAM.rar\\";
    String gurupath = "\\usr\\local\\apache-tomcat-8.5.31\\OSS-CPE-Tracker\\Zaky";

    
    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition", "attachment; filename=\""
            + gurufile + "\"");

    FileInputStream fileInputStream = new FileInputStream(gurupath
            + gurufile);

    int i;
    while ((i = fileInputStream.read()) != -1) {
        out.write(i);
    }
    fileInputStream.close();
    out.close();

1 个答案:

答案 0 :(得分:1)

此错误的唯一原因是无法在该路径下找到文件。

请验证路径

    String gurufile = "QCAM.rar\\";
    String gurupath = "\\usr\\local\\apache-tomcat-8.5.31\\OSS-CPE-Tracker\\Zaky";
    // <...>
    FileInputStream fileInputStream = new FileInputStream(gurupath
            + gurufile);

unix系统中,文件路径是使用正斜杠/而非反斜杠\解析的。

尝试更改为与upload脚本相同的值:

    FileInputStream fileInputStream = new FileInputStream("/usr/local/apache-tomcat-8.5.31/OSS-CPE-Tracker/Zaky/QCAM.rar")

那应该做