Java 正在读取conf文件夹中的属性文件

Java 正在读取conf文件夹中的属性文件,java,properties,nullpointerexception,Java,Properties,Nullpointerexception,我有一个属性文件,它位于conf文件夹下。conf文件夹位于项目根目录下。我正在使用以下代码 public class PropertiesTest { public static void main(String[] args) { InputStream inputStream = PropertiesTest.class .getResourceAsStream("/conf/sampleprop.conf"); Properties prop =

我有一个属性文件,它位于conf文件夹下。conf文件夹位于项目根目录下。我正在使用以下代码

public class PropertiesTest {
 public static void main(String[] args) {
    InputStream inputStream = PropertiesTest.class
            .getResourceAsStream("/conf/sampleprop.conf");
    Properties prop = new Properties();
    try {
        prop.load(inputStream);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println(prop.getProperty("TEST"));
}
}
但我得到一个空指针异常

我试过使用

InputStream inputStream = PropertiesTest.class
        .getResourceAsStream("./conf/sampleprop.conf");

但所有这些都会导致null指针异常。 谁能帮忙吗。
提前感谢

方法试图使用调用资源的类的类加载器来定位和加载资源。理想情况下,它只能在类文件夹中找到文件。。相反,您可以使用带有相对路径的
FileInputStream

编辑

如果
conf
文件夹位于src下,那么您仍然可以使用
getResourceAsStream()

该路径将与您调用的
getRes..
方法中的类相对

如果不是

 try {
                FileInputStream fis = new FileInputStream("conf/sampleprop.conf");
                Properties prop = new Properties();
                prop.load(fis);
                System.out.println(prop.getProperty("TEST"));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
注意:这仅在eclipse中是独立应用程序/时才起作用。如果它是基于web的(例如,根将是Tomcat/bin),那么这将不起作用


我建议将配置文件复制到指定的位置,这样您就可以轻松访问了。如果总是复制文件“tomcat”根或应用程序根,则在一定程度上可以使用“System.getProperty”(“user.dir”)”。但是,如果要由外部方使用文件,最好将其复制到可配置的文件夹(C:\appconf)

中,请首先尝试恢复您的工作目录:

String workingDir = System.getProperty("user.dir");
System.out.println("Current working dir: " + workingDir);
然后很简单:

Properties propertiesFile = new Properties();
propertiesFile.load(new FileInputStream(workingDir+ "/yourFilePath"));
    String first= propertiesFile.getProperty("myprop.first");

您好,法比奥,您的代码工作起来很有魅力!但是您可能必须将项目根目录添加到类路径中

如果使用Maven,请将配置放在src/main/resources/conf/sampleprop.conf中

直接调用java时,使用java-classpath参数添加项目根目录。比如:

java -classpath /my/classes/dir:/my/project/root/dir my.Main

你能给我们做一个ASCII艺术图表,显示这个源文件相对于conf文件夹的位置吗|__src | | | | | | uuu sampleprop.conf您的PropertiesTest类在哪里/@user1407668尝试使用绝对路径。@user1407668尝试使用此PropertiesTest.class.getClassLoader().getResourceAsStream(“conf/sampleprop.conf”);它不在src之下。。。。conf和src在projectfolder下处于同一级别,这很好…因为我的是一个持续运行的独立应用程序,这将完成工作。。。谢谢
Properties propertiesFile = new Properties();
propertiesFile.load(new FileInputStream(workingDir+ "/yourFilePath"));
    String first= propertiesFile.getProperty("myprop.first");
java -classpath /my/classes/dir:/my/project/root/dir my.Main