2012-10-18 55 views
0

這適用於單元測試。我收到文件並可以打印內容。當我在服務器上部署這個時,我得到一個FilenotFoundExcpetion。這可能是什麼原因?我正在部署一個tomcat。在tomcat上部署應用程序時未找到文件

String path = "WebContent/images/image.jpeg"; 

FileSystemResource resource = new FileSystemResource(path); 

File image = resource.getFile(); 

回答

0
String path = "WebContent/images/image.jpeg"; 

這是一個相對路徑,部署在servlet容器(如Tomcat)時,它會是相對於你的部署目錄或Tomcat的主目錄。可能你不會有一個名爲Webconent的目錄。 WebContent的內容也許也許會在一場戰爭中。

我能想到的兩種解決方案

  • 使用getRealPath方法,如果你有機會獲得requestServletContext
  • 使用ClassPathResource如果你可以把你的文件WEB-INF\classes
+0

String path = request.getRealPath(「」)+「/images/image.jpeg」;儘管getRealPath已被棄用。 – pethel

0

將Web應用程序部署到服務器上時,WebContent文件夾是隱含的。

當在web服務器使用的上下文中執行時 String path =「/images/image.jpeg」;

使用Class.getResourceAsStream()

1

使用上下文路徑爲您的工作項目帶來位置,然後您可以存儲您自己的路徑,就像您提到的images/image.jpg

String path = request.getSession().getContextPath().getRealPath("/")+"images/image.jpg"; 

我想它會幫助你!

相關問題