简体   繁体   English

读取与类相同目录的配置文件返回null

[英]Reading configuration file same directory as class returns null

I am not sure why I cannot read my configuration file which is in the same level as my class. 我不确定为什么无法读取与我的课程处于同一级别的配置文件。 I have tried both code below but both inputstreams are null. 我已经尝试了下面的两个代码,但两个inputstreams为null。

public MyClass
    public void getConfigurations()
    {
        String fileName = "myFile.conf";

        InputStream in = this.getClass().getResourceAsStream(fileName);
        InputStream inNew = this.getClass().getClassLoader().getResourceAsStream(fileName);
        System.out.println(in);
        System.out.println(inNew);
    }
    public static void main(String[] arg){
        MyClass myClass = new MyClass();
        myClass.getConfigurations();
    }
}

The output is: 输出为:

null
null

Here is my directory 这是我的目录

MyProject
    -src
        -com
            -test
                -MyClass.java
                -myFile.conf
    -lib

I am going to package this class into an executable jar file so I would like it to work in both windows and linux. 我将把此类打包到一个可执行的jar文件中,因此我希望它在Windows和Linux中都能工作。 When I package the jar file, I want the configuration file to be on the same level as my class. 打包jar文件时,我希望配置文件与我的类处于同一级别。

Did I miss something? 我错过了什么?

If you don't use absolute path (path beginning with / ), in this situation you cannot get your file location. 如果您不使用绝对路径(以/开头的路径),那么在这种情况下,您将无法获取文件位置。

Because you execute .class file, not the .java file. 因为您执行的是.class文件,而不是.java文件。 If you build your class in another folder, with relative path, your path is based on where the .class file is. 如果您在具有相对路径的另一个文件夹中构建类,则您的路径基于.class文件所在的位置。

Try to put class file in the same dir as java files. 尝试将类文件放在与Java文件相同的目录中。 I guess now you put them in build folder. 我想现在您将它们放在build文件夹中了。

Or, try to get them like /src/com/test . 或者,尝试使它们像/src/com/test This is absolute path. 这是绝对路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM