這適用於單元測試。我收到文件並可以打印內容。當我在服務器上部署這個時,我得到一個FilenotFoundExcpetion。這可能是什麼原因?我正在部署一個tomcat。在tomcat上部署應用程序時未找到文件
String path = "WebContent/images/image.jpeg";
FileSystemResource resource = new FileSystemResource(path);
File image = resource.getFile();
這適用於單元測試。我收到文件並可以打印內容。當我在服務器上部署這個時,我得到一個FilenotFoundExcpetion。這可能是什麼原因?我正在部署一個tomcat。在tomcat上部署應用程序時未找到文件
String path = "WebContent/images/image.jpeg";
FileSystemResource resource = new FileSystemResource(path);
File image = resource.getFile();
String path = "WebContent/images/image.jpeg";
這是一個相對路徑,部署在servlet容器(如Tomcat)時,它會是相對於你的部署目錄或Tomcat的主目錄。可能你不會有一個名爲Webconent的目錄。 WebContent的內容也許也許會在一場戰爭中。
我能想到的兩種解決方案
的getRealPath
方法,如果你有機會獲得request
或ServletContext
ClassPathResource
如果你可以把你的文件WEB-INF\classes
將Web應用程序部署到服務器上時,WebContent文件夾是隱含的。
當在web服務器使用的上下文中執行時 String path =「/images/image.jpeg」;
也
使用Class.getResourceAsStream()
使用上下文路徑爲您的工作項目帶來位置,然後您可以存儲您自己的路徑,就像您提到的images/image.jpg
String path = request.getSession().getContextPath().getRealPath("/")+"images/image.jpg";
我想它會幫助你!
String path = request.getRealPath(「」)+「/images/image.jpeg」;儘管getRealPath已被棄用。 – pethel