简体   繁体   English

getResourceAsStream() 返回 null。 未加载属性文件

[英]getResourceAsStream() is returning null. Properties file is not loading

I am trying to load properties file.我正在尝试加载属性文件。 Here is my structure这是我的结构

目录结构

Now i am trying to load test.properties file.现在我正在尝试加载 test.properties 文件。 But i am getting null.但我越来越空了。 Here how i am doing在这里我是怎么做的

public class Test {

    String workingDir = System.getProperty("user.dir");
    System.out.println("Current working directory : " + workingDir);

    File temp = new File(workingDir + "\\" + "test.properties");
    String absolutePath = temp.getAbsolutePath();
    System.out.println("File path : " + absolutePath);

    Properties properties = null;

    try {
        properties = new Properties();
        InputStream resourceAsStream =  Test.class.getClassLoader().getResourceAsStream(absolutePath);
        if (resourceAsStream != null) {
            properties.load(resourceAsStream);
        }


    } catch (IOException e) {
        e.printStackTrace();
    }

    System.exit(0);

} //end of class Test

This program prints这个程序打印

Current working directory : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration
File path : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration\test.properties

But it is not loading properties file from this path.但它没有从这个路径加载属性文件。 Although it is present there.虽然它存在于那里。 Why i am getting null ?为什么我得到 null ?

Thanks谢谢

Edit--- ----------------------------编辑-------------------------------

String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);

File temp = new File(workingDir, "test.properties");

String absolutePath = temp.getAbsolutePath();
System.out.println("File path : " + absolutePath);

try {
    properties = new Properties();
    InputStream resourceAsStream =  new FileInputStream(temp);
    if (resourceAsStream != null) {
        properties.load(resourceAsStream);
    }   
} catch (IOException e) {
    e.printStackTrace();
}

System.exit(0);

Current working directory : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration
File path : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration\test.properties
java.io.FileNotFoundException: D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration\test.properties (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at com.softech.ls360.integration.BatchImport.main(BatchImport.java:57)

Oh oh ... There are several problems here:哦哦……这里有几个问题:

1) In your first provided code snippet, you are using a ClassLoader for loading a resource file. 1) 在您提供的第一个代码片段中,您使用ClassLoader加载资源文件。 This is indeed a good decision.这确实是一个很好的决定。 But the getResourceAsStream method needs a "class-path relative" name.但是getResourceAsStream方法需要一个“类路径相关”名称。 You are providing an absolute path.您提供的是绝对路径。

2) Your second code snippet (after edit) results in not being able to find the file "D:...\\LS360BatchImportIntegration\\test.properties". 2)您的第二个代码片段(编辑后)导致无法找到文件“D:...\\LS360BatchImportIntegration\\test.properties”。 According to your screenshot, the file should be "D:...\\LS360AutomatedRegulatorsReportingService\\test.properties".根据您的屏幕截图,该文件应为“D:...\\LS360AutomatedRegulatorsReportingService\\test.properties”。 This is another directory.这是另一个目录。

I fear, that your descriptions are not up to date with the findings on your machine.我担心,您的描述与您机器上的发现不符。

But let's just move to a reasonable solution:但让我们转向一个合理的解决方案:

1) In your Eclipse project (the screenshot tells us, that you are using Eclipse), create a new directory named "resources" in the same depth as your "src" directory. 1) 在您的 Eclipse 项目中(截图告诉我们,您正在使用 Eclipse),创建一个名为“resources”的新目录,其深度与您的“src”目录相同。 Copy - or better move - the properties file into it.复制 - 或者更好地移动 - 属性文件到其中。

2) This new directory must be put into the "build path". 2) 这个新目录必须放在“构建路径”中。 Right-click the directory in the Package Explorer or Project Explorer view, select "Build Path", then "Use as Source Folder".右键单击 Package Explorer 或 Project Explorer 视图中的目录,选择“Build Path”,然后选择“Use as Source Folder”。 Note: This build path will be the class path for the project, when you run it.注意:当您运行它时,此构建路径将是项目的类路径。

3) As the resources directory now is part of your class path and contains your properties file, you can simply load it with getResourceAsStream("test.properties") . 3) 由于资源目录现在是您的类路径的一部分并包含您的属性文件,您可以简单地使用getResourceAsStream("test.properties")加载它。

EDIT编辑

I just see, that you also use Maven (the pom.xml file).我只是看到,您还使用了 Maven(pom.xml 文件)。 In Maven, such a resources directory exists by default and is part of the build path.在 Maven 中,这样的资源目录默认存在并且是构建路径的一部分。 It is "src/main/resources".它是“src/main/resources”。 If so, just use this.如果是这样,只需使用它。

Please put your property file in /src/main/resources folder and load from ClassLoader.请将您的属性文件放在 /src/main/resources 文件夹中并从 ClassLoader 加载。 It will be fix.它会被修复。

like

 /src/main/resources/test.properties



Properties properties = null;

try {
    properties = new Properties();
    InputStream resourceAsStream =  Test.class.getClassLoader().getResourceAsStream("test.properties");
    if (resourceAsStream != null) {
        properties.load(resourceAsStream);
    }


} catch (IOException e) {
    e.printStackTrace();
}

You are using the class loader (which reads in the classpath) whereas you are using the absolute path.您正在使用类加载器(在类路径中读取),而您正在使用绝对路径。

Simply try:只需尝试:

InputStream resourceAsStream =  new FileInputStream(temp);

As a side note, try instanciating your file doing:作为旁注,请尝试实例化您的文件:

File temp = new File(workingDir, "test.properties");

to use the system-dependent path spearator.使用依赖于系统的路径分隔符。

I had a similar problem with a file not being found by getResourceAsStream() .我在getResourceAsStream()找不到文件时遇到了类似的问题。 The file was in the resources folder ( src/main/resources ), and still not found.该文件位于资源文件夹 ( src/main/resources ) 中,但仍未找到。

The problem got resolved when I went into the eclipse Package Explorer and "refreshed" the resources folder.当我进入 eclipse Package Explorer 并“刷新”资源文件夹时,问题得到了解决。 It was in the directory, but Eclipse did not see it until the folder was refreshed (right-click on the folder and select Refresh).它在目录中,但是直到刷新文件夹(右键单击文件夹并选择刷新)后,Eclipse 才看到它。

I hope this helps !!我希望这会有所帮助!! You can keep your test.properties into src/main/resources您可以将 test.properties 保存到 src/main/resources

 public static Properties props = new Properties();
    InputStream inStream = Test.class.getResourceAsStream("/test.properties");
    try {
            loadConfigurations(inStream);
        } catch (IOException ex) {
            String errMsg = "Exception in loading configuration file. Please check if application.properties file is present in classpath.";
            ExceptionUtils.throwRuntimeException(errMsg, ex, LOGGER);
        }
    public static void loadConfigurations(InputStream inputStream) throws IOException{
            props.load(inputStream);
        }

You're passing a file path to getResourceAsStream(String name) , but name here is a class path, not a file path...您将文件路径传递给getResourceAsStream(String name) ,但这里的name是类路径,而不是文件路径...

You could make sure the file is on your classpath, or use a FileInputStream instead.您可以确保该文件在您的类路径上,或者改用FileInputStream

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

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