如何在EclipseJava动态Web项目中读取属性文件?
我想我确实想做他做的事 但对我来说有点不同。我首先检查文件是否存在:如何在EclipseJava动态Web项目中读取属性文件?,java,eclipse,file,Java,Eclipse,File,我想我确实想做他做的事 但对我来说有点不同。我首先检查文件是否存在: File f = new File("properties.txt"); System.out.println(f.exists()); 我没有另一篇文章中描述的文件夹/project/WebContent/WEB-INF/classes,但我编译的类位于/project/build/classes中,因此我将属性文件放在那里(确切地说:在我访问该文件的类的包文件夹中) 但它仍然打印false。可能是我做错了,如果是这样,请
File f = new File("properties.txt");
System.out.println(f.exists());
我没有另一篇文章中描述的文件夹/project/WebContent/WEB-INF/classes
,但我编译的类位于/project/build/classes
中,因此我将属性文件放在那里(确切地说:在我访问该文件的类的包文件夹中)
但它仍然打印
false
。可能是我做错了,如果是这样,请告诉我。如果您的文件位于类路径或类文件夹中,而不仅仅是从类路径获取路径。不要对java.io.File
使用相对路径,它取决于您在java代码中没有控制的当前工作目录
您可以这样尝试:
URL url = getClass().getClassLoader().getResource("properties.txt");
File f = new File(url.getPath());
System.out.println(f.exists());
如果文件
properties.txt
位于在getResource(…)
函数中提供相对路径的任何包中。e、 ggetResource(“properties\\properties.txt”)
执行此操作的代码非常简单。让我们考虑一个名为<代码> SampleApp的战争文件.WAR ,它的属性文件名为“代码> MyApp.Frase根目录:
SampleApp.war
|
|-------- myApp.properties
|
|-------- WEB-INF
|
|---- classes
|
|----- org
|------ myApp
|------- MyPropertiesReader.class
假设您希望读取属性文件中名为abc的属性:
在myApp.properties
中:
abc = someValue;
xyz = someOtherValue;
让我们考虑在您的应用程序中存在的类<代码> org .MyApp.MyPrimeStRealeReule>代码,希望读取属性。下面是相同的代码:
package org.myapp;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Simple class meant to read a properties file
*
* @author Sudarsan Padhy
*
*/
public class MyPropertiesReader {
/**
* Default Constructor
*
*/
public MyPropertiesReader() {
}
/**
* Some Method
*
* @throws IOException
*
*/
public void doSomeOperation() throws IOException {
// Get the inputStream
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("myApp.properties");
Properties properties = new Properties();
System.out.println("InputStream is: " + inputStream);
// load the inputStream using the Properties
properties.load(inputStream);
// get the value of the property
String propValue = properties.getProperty("abc");
System.out.println("Property value is: " + propValue);
}
}
我把文件放在
/project/build/classes
下,尝试了你的建议。我在这一行中得到一个NullPointerException
文件f=new文件(url.getPath())代码>。之后,我尝试了System.out.println(url.getPath())
并且也得到了异常,因此类似乎无法访问该文件。它放错地方了吗?或者我必须像类路径一样进行更改吗?'GetResource(…)'参数中给出的路径是什么??确保文件位于您提供的.System.out.println(f.getAbsolutePath())路径上;