【问题标题】:Maven java.io.FileNotFoundExceptionMaven java.io.FileNotFoundException
【发布时间】:2012-05-08 11:38:04
【问题描述】:

我正在使用 Maven 开发一个项目。在发送电子邮件的类中,在运行和开发模式下,我收到以下错误: 引起:java.io.FileNotFoundException: jQuery/images/logo.png (Ficheiro ou directory inexistente) ==> translation = File 或找不到目录。

我尝试了很多路径,例如“./jQuery/images/logo.png”、“/jQuery/images/logo.png”等。完整的相对路径是:“src/main/webapp/jQuery/images/logo.png”。

在“target”文件夹中,路径为“project-1.0-SNAPSHOT/jQuery/images/logo.png”。 里面的war文件,是“jQuery/images/logo.png”。

我认为这并不重要,但我使用的是 NetBeans 7.1.1 作为 IDE。

我发现运行时返回的绝对路径是“/home/user/apache-tomcat-7.0.22/bin/jQuery/images/logo.png”!...不是项目路径!

如何在 Maven 项目中获取 webapp 文件夹中的文件和 Java 类的后代?

代码是:

MimeBodyPart attachmentPart = null;
        FileDataSource fileDataSource = null;
        for (File a : attachments) {
            System.out.println(a.getAbsolutePath());

            attachmentPart = new MimeBodyPart();
            fileDataSource = new FileDataSource(a) {

                @Override
                public String getContentType() {
                    return "application/octet-stream";
                }
            };
            attachmentPart.setDataHandler(new DataHandler(fileDataSource));
            attachmentPart.setFileName(fileDataSource.getName());

            multipart.addBodyPart(attachmentPart);
        }

        msg.setContent(multipart);
        msg.saveChanges();

        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, "password");
        transport.sendMessage(msg, msg.getAllRecipients());

【问题讨论】:

  • 显示您用来打开文件的代码。
  • 感谢您的快速回复!

标签: maven filenotfoundexception


【解决方案1】:

.../apache-tomcat-7.0.22/bin/jQuery/... 的路径真的很奇怪。 bin 包含 Tomcat 的脚本,它不应包含任何代码或与您的应用程序相关的任何资源。即使您在上下文/bin 中部署您的应用程序,资源最终也会在`.../apache-tomcat-7.0.22/webapps/bin/...

这看起来像是在早期部署中犯的一个错误。

现在回到你的问题。要获取您的网络应用程序的资源路径,请使用以下代码:

String absolutePath = getServletContext().getRealPath("/jQuery/images/logo.png");

(docs)

【讨论】:

  • 我没有使用 servlet。是一个普通的 Java 类,如果我可以这样称呼它... public class EmailsManager {...}
  • 在那个类中,使用 System.getProperty("java.class.path") 我得到:/home/user/apache-tomcat-7.0.22/bin/bootstrap.jar:/home/ rcc/apache-tomcat-7.0.22/bin/tomcat-juli.jar。这是什么意思?
  • 好吧,我们做到了!谢谢亚伦。我在调用 Java 类的 JSP 中使用了您的建议。 JSP中使用的新代码是:String attachment = (String) request.getParameter("attachment"); // 单个演示文件 String attachmentRealPath = request.getSession().getServletContext().getRealPath(attachment + "/"); ArrayList 附件 = new ArrayList();附件.add(new File(attachmentRealPath)); EmailsManager emails = new EmailsManager(host,port,from,to,subject,bodyText,attachments);
  • 对不起,代码行应该分开,但我没有找到这样做的方法。
猜你喜欢
  • 1970-01-01
  • 2017-09-15
  • 1970-01-01
  • 2013-04-21
  • 2014-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多