我想用来从Web应用程序的外部读取属性文件。我在Windows环境中的tomcat中部署了war文件,并且可以使用以下代码从Web应用程序外部读取属性文件。
//(Method 1.)
String filePath =
new java.io.File( ".").getCanonicalPath()+"/webapps/strsproperties/strs.properties";
// or
//(Method 2.)
String filePath = new File(System.getProperty("catalina.base"))+ "/webapps/strsproperties/strs.properties";
InputStream inputStream = null;
inputStream = new FileInputStream(filePath);
properties.load(inputStream);
String application = properties.getProperty("applications");
在以上两种情况下,我都可以在Windows中读取filePath。
问题是我无法使用第一种方法(相对路径)过程在Linux中读取filePath。
有什么方法可以从Linux env使用tomcat中的相对路径读取文件?
您的问题是您不知道“当前”目录是什么。如果您将Tomcat作为服务启动在Linux上,则当前目录可以是任何目录。因此,new File(".")
您将在文件系统中获得一个随机位置。
使用system属性catalina.base
要好得多,因为Tomcat的启动脚本catalina.sh
将设置此属性。因此,只要您不尝试在其他服务器上运行应用程序,此方法就可以工作。
好的代码如下所示:
File catalinaBase = new File( System.getProperty( "catalina.base" ) ).getAbsoluteFile();
File propertyFile = new File( catalinaBase, "webapps/strsproperties/strs.properties" );
InputStream inputStream = new FileInputStream( propertyFile );
如您所见,该代码不会混合字符串和文件。文件是文件,字符串只是文本。避免使用文本作为代码。
接下来,我要getAbsoluteFile()
确保在异常中得到有用的路径。
还要确保您的代码不会吞下异常。如果您可以在代码中看到错误消息,则可以立即看到该代码试图在错误的位置查找。
最后,这种方法很脆弱。如果路径更改,使用其他Web服务器以及许多其他情况,您的应用程序就会中断。
考虑将webapp扩展strsproperties
为接受HTTP请求。这样,您可以将应用程序配置为strsproperties
通过URL 连接。这适用于任何Web服务器,甚至可以将属性放在其他主机上。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句