Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 何时使用;getResourceAsStream";方法?_Java_Properties - Fatal编程技术网

Java 何时使用;getResourceAsStream";方法?

Java 何时使用;getResourceAsStream";方法?,java,properties,Java,Properties,我对使用上述方法感到困惑,因为在加载某些属性文件时,人们采用了不同的方法 Properties prop = new Properties(new FileInputStream(new File("<path of the properties file>")); 属性属性属性 =新属性(新文件输入流(新文件(“”)); 而且很少有人使用 Properties prop = new Properties(getClass().getResourceAsStream("&

我对使用上述方法感到困惑,因为在加载某些属性文件时,人们采用了不同的方法

Properties prop 
 = new Properties(new FileInputStream(new File("<path of the properties file>"));
属性属性属性
=新属性(新文件输入流(新文件(“”));
而且很少有人使用

Properties prop 
 = new Properties(getClass().getResourceAsStream("<path of the properties file>"));
属性属性属性
=新属性(getClass().getResourceAsStream(“”);

当使用哪种方法时?

如果您100%确定文件位置不会在不同环境中更改,则可以使用第一种方法。这意味着有一个操作可以确保在所有环境中创建这些目录路径。另一方面,您可以灵活地更新属性文件,而无需打开罐子

第二种方法在读取类路径时非常可移植,但它的缺点是每次属性更新都要重新绑定jar文件


因此,它基本上取决于您的用例。

getResourceAsStream
搜索给定文件/资源的类路径,它还可以从JAR中提供资源的
InputStreams


因此,如果您的属性存在于物理文件系统中的某个文件夹中(例如,用户文件夹,…),请使用
FileInputStream
,如果该文件嵌入在您的类路径中(例如,作为JAR中的资源),则在从文件系统读取文件时,请使用
getResourceAsStream

使用相对或绝对路径


当您的程序作为jar分发并且需要加载jar中的文件时,您需要使用getResourceAsStream(),它将在类路径中搜索文件,该路径与类路径相对。

当您从Jar读取文件时。请使用classloader的getResource或GetResourceReastream。查找下面的代码段从Jar读取文件。上述方法无法从Jar读取文件

    InputStream in = this.getClass().getClassLoader()
            .getResourceAsStream("com/net/resources/config.properties");

    InputStream is = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("com/net/resources/config.properties");

    URL url = this.getClass().getClassLoader()
            .getResource("com/net/resources/config.properties");

微小nit的可能重复-缺少1个右括号