小编典典

从Java到Tomcat路径的访问

tomcat

我有一个在本地Tomcat中运行的webapp。路径是:tomcat/webapps/myproject
我在这个项目中有一些资源,都在以下路径的文件夹中:tomcat/webapps/myproject/resources

因此,我正在尝试使用file来访问Java项目中的这些资源config.properties。在这个文件中,我有这样的东西:

tomcat.url= http://localhost
tomcat.port=8080
tomcat.resources=/myproject/resources

我也尝试了/或的不同组合,\但在运行项目时遇到此错误:

Trying to acces to a directory that does not exist

我的Java代码:

Configuration config = new PropertiesConfiguration("config.properties");    
String sourcePath = config.getString("tomcat.resources");
//And I try to list this folder  
File dir = new File(sourcePath);
String[] children = dir.list();         
if (children == null) {          
    // Either dir does not exist or is not a directory
    throw new ServiceExecutionException("Trying to generate Metadata in a directory that does not exist");                  
}

我不知道出什么问题了,在我之前做过的项目中,与此类似,我有类似的东西,它找到了一切。
有任何想法吗??提前致谢。


阅读 275

收藏
2020-06-16

共1个答案

小编典典

该文件必须位于“tomcat/webapps/myproject/src/main/resources检查更新”中。

我不知道您如何访问文件,但是以防万一我建议您使用PropertiesConfiguration

 private static final String CONFIGURATION_PATH = "config.properties";
 PropertiesConfiguration configuration = new PropertiesConfiguration(CONFIGURATION_PATH);

已编辑

问题是,/myproject/resources当文件位于(可能)时,您正在尝试打开一个文件(请记住,“
/”是您的根文件系统)/var/lib/tomcat6/webapps/myproject/resources

您可以使用ServletContext#getRealPath获得文件的真实路径

2020-06-16