简体   繁体   English

如何在Java中指定getResourceAsStream()方法的路径

[英]How to specify the path for getResourceAsStream() method in java

I know this question has been asked several times but I still can't get it work by those solutions. 我知道这个问题已经被问过几次了,但是这些解决方案仍然无法解决这个问题。

I have a maven project. 我有一个Maven项目。 And one Config.java file located in consumer/src/main/java . 还有一个位于consumer/src/main/java Config.java文件。 Here's the content: 内容如下:

import java.util.Properties;

public class Config {
    Properties configFile;
    public Config() {
        configFile = new Properties();
        try {
            configFile.load(this.getClass().getClassLoader().
                    getResourceAsStream("property_table.config.txt"));
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public String getProperty(String key) {
        String value = this.configFile.getProperty(key);
        return value;
    }
    public static void main(String[] args) {
        Config config = new Config();
        System.out.println("URL: " + config.getProperty("URL"));
        System.out.println("PASSWORD: " + config.getProperty("PASSWORD"));
    }
}

I kept getting nullpointer exception . 我不断收到nullpointer exception I know that's because it can't find the file property_table.config.txt . 我知道这是因为找不到文件property_table.config.txt

At first I put the property_table_config.txt file in the same folder( consumer/src/main/java/ ) as Config.java file. 首先,我将property_table_config.txt文件与Config.java文件放在同一文件夹( consumer/src/main/java/ )中。 And tried use /property_table_config.txt and 'property_table_config.txt`. 并尝试使用/property_table_config.txt和'property_table_config.txt`。 Neither of them work. 他们都不工作。

And then I tried using absolute path, not working. 然后我尝试使用绝对路径,无法正常工作。 And tried using /main/java/property_table_config , not working either. 并尝试使用/main/java/property_table_config ,也不起作用。

Then I saw this solution: https://stackoverflow.com/a/2103625/8159477 . 然后我看到了这个解决方案: https : //stackoverflow.com/a/2103625/8159477 So I make a directory called resources and put it under main folder (ie the path of the folder is consumer/src/main/resources , and create a sub-folder config under resources . After putting the property_table_config.txt file there, I changed the code into this: 因此,我创建了一个名为resources的目录,并将其放在主文件夹下(即,该文件夹的路径为consumer/src/main/resources ,并在resources下创建一个子文件夹config 。在此处将property_table_config.txt文件放入后,我进行了更改代码如下:

configFile.load(this.getClass().getClassLoader().getResourceAsStream("/config/property_table.config.txt"));

But this still didn't work. 但这仍然行不通。 Can anyone give some hint on this? 有人可以对此提供一些提示吗? Any suggestions will be appreciated!! 任何建议将不胜感激!

According to the Class.getResourceAsStream : 根据Class.getResourceAsStream

This method delegates to this object's class loader. 该方法委托给该对象的类加载器。 If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResourceAsStream. 如果此对象是由引导类加载器加载的,则该方法将委托给ClassLoader.getSystemResourceAsStream。

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm: 在委派之前,使用以下算法从给定资源名称构造绝对资源名称:

  • If the name begins with a '/' ('\/'), then the absolute name of the resource is the portion of the name following the '/'. 如果名称以'/'('\\ u002f')开头,则资源的绝对名称是名称中'/'之后的部分。
  • Otherwise, the absolute name is of the following form: 否则,绝对名称的格式如下:
    modified_package_name/name
    Where the modified_package_name is the package name of this object with '/' substituted for '.' 其中Modifyed_pa​​ckage_name是此对象的软件包名称,用“ /”代替“。”。 ('\.'). ( '\\ u002e')。

This is how I understand the comments: 这就是我对评论的理解:

  • If you use ClassLoader.getResourceAsStream , send the absolute path from package root, but omitting the first / . 如果使用ClassLoader.getResourceAsStream ,则从包根目录发送绝对路径,但省略第一个/
  • If you use Class.getResourceAsStream , send either a path relative the the current Class object (and the method will take the package into account), or send the absolute path from package root, starting with a / . 如果使用Class.getResourceAsStream ,则发送相对于当前Class对象的路径(该方法将考虑包),或者从包根目录以/开头发送绝对路径。

But in addition to this, you need to be cognizant of your build system. 但是除此之外,您还需要了解自己的构建系统。 With maven, resource files are stored under src/main/resources . 使用maven,资源文件存储在src/main/resources

So, in your case, I believe making the following changes should resolve the issue: 因此,就您而言,我相信进行以下更改应该可以解决此问题:

  • Put the file in src/main/resources . 将文件放在src/main/resources
  • Change the code to 将代码更改为

     this.getClass() .getResourceAsStream("/property_table.config.txt") //or `Config.class.getResource... 
  • Alternatively, use 或者,使用

      this.getClass().getClassLoader() .getResourceAsStream("property_table.config.txt")` 

I've tried this with a similar setup, and it works as expected. 我已经用类似的设置尝试过,它可以按预期工作。

ClassLoader().getResourceAsStream() is looking files only in classpath. ClassLoader().getResourceAsStream()仅在类路径中查找文件。 What you need is to have your config file in directory which is in classpath. 您需要将配置文件放在类路径中的目录中。

So, you have options: 因此,您可以选择:

  • when you run your java application from command line you can set path to directory in -cp parameter or CLASSPATH system variable. 从命令行运行Java应用程序时,可以在-cp参数或CLASSPATH系统变量中设置目录的路径。 point there is: directory from where you need to get config file must be in class path - not a file. 要点是:您需要从中获取配置文件的目录必须位于类路径中,而不是文件中。 (eg if file location is c:\\my_projects\\test-project\\config\\my_config.properties and c:\\my_projects\\test-project\\ is in classpath then getResourceAsStream call will be ClassLoader().getResourceAsStream("config/my_config.properties") (例如,如果文件位置为c:\\my_projects\\test-project\\config\\my_config.propertiesc:\\my_projects\\test-project\\位于类路径中,则getResourceAsStream调用将为ClassLoader().getResourceAsStream("config/my_config.properties")

  • you can package your file into jar file and root of jar file is starting point for getResourceAsStream("config/my_config.properties") 您可以将文件打包到jar文件中,并且jar文件的根是getResourceAsStream("config/my_config.properties")起点

  • If your Maven project is a jar project you need to use Maven resource plugin to put additional resource(s) into jar. 如果您的Maven项目是jar项目,则需要使用Maven资源插件将其他资源放入jar。

BTW: Maven does not put anything into jar file from src/main/java/ directory (if you do not explicitly specify it for resource plugin) 顺便说一句:Maven不会将任何文件放入src / main / java /目录的jar文件中(如果您未为资源插件明确指定它)

If you use IDE like Eclipse with your Maven project src/main/resources is a part of build classpath. 如果您在Maven项目中使用类似Eclipse的IDE,则src / main / resources是构建类路径的一部分。 Double check is it there and if it is not - do "Update Maven Project" or add it manually. 请仔细检查是否存在,如果不存在,请进行-“更新Maven项目”或手动添加。

Still ClassLoader will see your properties file from src/main/resources folder only when you run project in IDE not from standalone Jar file - if you did not package your file or provide location in classpath. 仅当您在IDE中运行项目而不是从独立的Jar文件中运行时(如果您没有打包文件或未在classpath中提供位置时),ClassLoader仍然会从src / main / resources文件夹中看到您的属性文件。

Can you try following code. 您可以尝试以下代码吗?

Config.class.getResourceAsStream("property_table.config.txt") Config.class.getResourceAsStream( “property_table.config.txt”)

Update: This is the code I tried. 更新:这是我尝试的代码。

package test;

import java.util.Properties;

public class Config
{
  Properties configFile;

  public Config()
  {
    configFile = new Properties();
    try
    {
      configFile.load(Config.class.getResourceAsStream("property_table.config.txt"));
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  public String getProperty(String key)
  {
    String value = this.configFile.getProperty(key);
    return value;
  }

  public static void main(String[] args)
  {
    Config config = new Config();
    System.out.println("URL: " + config.getProperty("URL"));
    System.out.println("PASSWORD: " + config.getProperty("PASSWORD"));
  }
}

And I placed property_table.config.txt file withn test package and it worked. 然后,我将property_table.config.txt文件与测试包一起放置,它可以正常工作。

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

相关问题 JAVA getResourceAsStream()文件的真实路径字符串解释 - JAVA getResourceAsStream() real path string interpretation of a file getClassLoader().getResourceAsStream() 如何在 Java 中工作 - How getClassLoader().getResourceAsStream() works in java 如何在XML文件中使用SynthLookAndFeel,其中xml文件路径将使用getResourceAsStream方法加载文件? - How to use SynthLookAndFeel with xml file, where xml file path will load the file using getResourceAsStream method? 如何在 Java 中指定文件路径? - How to specify path to file in Java? 如何使用Java方法Class.getResourceAsStream()从jar中读取UTF-8文本文件? - How can I read a UTF-8 text file from a jar using the Java method Class.getResourceAsStream()? Java getResourceAsStream带来麻烦,混淆了包的工作方式 - Trouble With Java getResourceAsStream, confusion with how Packages work 如何在 java 中模拟 InputStream getResourceAsStream? - How can I mock InputStream getResourceAsStream in java? 如何为Java代理指定类路径 - how to specify class path for java agent 如何在Java源代码中指定jar的路径? - How to specify the path to jar in java source code? 如何在Hadoop上的Java / terminal中指定文件的路径? - How to specify path of a file in java/terminal on Hadoop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM