Java 如何读取属性文件?
我想从名为jdbc.properties的属性文件中读取一行。它位于Java 如何读取属性文件?,java,file,properties,Java,File,Properties,我想从名为jdbc.properties的属性文件中读取一行。它位于src\main\webapp\WEB-INF\db\jdbc.properties中。我应该走哪条路? 这是我的方法: Properties prop = new Properties(); try { // load a properties file prop.load(new FileInputStream("jdbc.properties"));
src\main\webapp\WEB-INF\db\jdbc.properties
中。我应该走哪条路?
这是我的方法:
Properties prop = new Properties();
try {
// load a properties file
prop.load(new FileInputStream("jdbc.properties"));
System.out.println(prop.getProperty("password"));
} catch (IOException ex) {
ex.printStackTrace();
}
您需要指定
FileInputStream
的绝对路径。您可以通过调用servletContext.getRealPath(“/WEB-INF/db/jdbc.properties”)
如果您没有可用的
servletContext
(通过.getServletContext()
),那么您应该将它(或应用程序根目录的绝对路径)传递给上面的代码。是否为TOMCAT\u HOME设置了环境变量,如果没有设置它
现在你可以使用
/webapps//web-inf/db/jdbc.properties
要获取环境变量的值,请使用以下代码:
Map<String, String> env = System.getenv();
Map env=System.getenv();
干杯 如果您将属性文件移动到
src/main/resources
,假设您的项目由maven管理,那么您可以通过
Properties prop = new Properties();
try {
// load a properties file
prop.load(YourClass.class.getResourceAsStream("/jdbc.properties")); // note the leading /
System.out.println(prop.getProperty("password"));
} catch (IOException ex) {
ex.printStackTrace();
}
其中,YourClass
是该代码所在的任何类
Maven将编译类的类文件和所有资源放在src/main/resources
的WEB-INF/classes
中,只有应用程序可以访问它们
如果将文件放入src/main/resources/someFolder
,则需要从
prop.load(YourClass.class.getResourceAsStream("/someFolder/jdbcProperties"));
您提供给上述方法的路径是相对于您所在类的包的,除非您指定了前导正斜杠,在这种情况下,它将相对于类路径的根,即
classes
文件夹。I添加了第二段。我不知道您的代码驻留在哪里,所以我假设它位于servletUse类中。GetResourceAsstream将属性文件导出到src/main/resources
中,并使用类加载器访问它。但我认为,如果不是在webinf中,每个人都可以看到我的数据。这是我的密码。编译源代码时,类文件和src/main/resources
中的所有内容都将被放入WEB-INF/classes
中,所以不用担心。完成。那么我应该如何处理我的代码呢?哪条路?看下面我的答案。相同的ish代码,只需更改将InputStream
获取到该属性资源的方式。