java FileNotFoundException(是一个目录)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29764129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:53:49  来源:igfitidea点击:

FileNotFoundException (Is a Directory)

javajakarta-eefile-uploadmultipartform-data

提问by Sandeep Rao

I am currently trying to upload multiple files, and the files are being upload properly into the destination directory. But in the logs it is giving me this error:

我目前正在尝试上传多个文件,并且这些文件正在正确上传到目标目录中。但是在日志中它给了我这个错误:

java.io.FileNotFoundException: /home/sandeep/java_proj/jee_tut/files (Is a directory)

at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
at java.io.FileOutputStream.<init>(FileOutputStream.java:171)
at com.jee.controller.FileProcessing.uploadFiles(FileProcessing.java:35)
at com.jee.controller.View.doPost(View.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

This is my code for uploading the files:

这是我上传文件的代码:

final String UPLOAD_DIR="files";

    String applicationPath="/home/sandeep/java_proj/jee_tut";
    String uploadDirPath= applicationPath + File.separator + UPLOAD_DIR;

    try{
        File fileDir=new File(uploadDirPath);
        if(!fileDir.exists()){
            fileDir.mkdirs();
        }
        InputStream inputStream= null;
        OutputStream outputStream = null;
        try{
            for(Part part:request.getParts()){
                String fileName=getFileName(part);

                    File outputPath=new File(uploadDirPath + File.separator + fileName);
                    inputStream = part.getInputStream();
                    outputStream = new FileOutputStream(outputPath);

                    int read = 0;
                    final byte[] bytes = new byte[1024];
                    while((read=inputStream.read(bytes)) != -1){
                        outputStream.write(bytes, 0, read);
                    }
                System.out.println(fileName);
            }
        }catch(Exception e){
            e.printStackTrace();
            return "";
        }
        finally{
            if(inputStream != null){
                inputStream.close();
            }
            if(outputStream != null){
                outputStream.close();
            }
        }
        return uploadDirPath;

    }catch(Exception e){
        e.printStackTrace();
        return "";
    }

As I am new to java, I'm not sure why it is giving me this error. How do I debug this?

由于我是 Java 新手,我不确定为什么会出现此错误。我该如何调试?

回答by Jens

Looks like in some cases filenameis blank or null so File outputPath=new File(uploadDirPath + File.separator + fileName);will be a directory and here new FileOutputStream(outputPath);you try to write to a directory not to a file. So you should check if filenameis not blank.

看起来在某些情况下filename为空或空,因此File outputPath=new File(uploadDirPath + File.separator + fileName);将是一个目录,在这里new FileOutputStream(outputPath);您尝试写入目录而不是文件。所以你应该检查是否filename不为空。

回答by fge

You have many errors in your code. For one, you only close the lastInputStreams and OutputStreams; you should close each of them. The way you do things here, you have a resource leak.

您的代码中有很多错误。一方面,你只关闭最后的InputStreams 和OutputStreams;你应该关闭它们中的每一个。你在这里做事的方式,你有资源泄漏。

Second, this is 2015; therefore drop Fileand use java.nio.file instead; plus, use try-with-resources.

第二,这是2015年;因此删除File并使用 java.nio.file 代替;另外,使用 try-with-resources。

Third: right now you upload in the project directory; don't do that when the application runs "live" on a server, this obviously won't work.

第三:现在你在项目目录中上传;当应用程序在服务器上“实时”运行时,不要这样做,这显然是行不通的。

Sample:

样本:

private static final Path BASEDIR = Paths.get("/path/to/upload/directory");

// in the upload method:

Files.createDirectories(BASEDIR);

String fileName;
Path path;

for (final Part part: request.getParts()) {
    fileName = getFileName(part);

    if (fileName.isEmpty())
        continue;

    path = BASEDIR.resolve(fileName);

    try (
        final InputStream in = part.getInputStream();
    ) {
        Files.copy(in, path, StandardOpenOption.CREATE_NEW);
    }
}

回答by Manohar Reddy

This error occured to me because I was using file.mkdirs()with complete fileName .

这个错误发生在我身上,因为我使用的file.mkdirs()是完整的 fileName 。

Suppose your file path is emulated/0/test/images/img.jpg

假设你的文件路径是 emulated/0/test/images/img.jpg

Then remove last part from the path and use file.mkdirs()on result file

然后从路径中删除最后一部分并file.mkdirs()在结果文件上使用

File file=new File("emulated/0/test/images/")
  if(!file.exists()){
       file.mkdirs();
   }