[英]Use FileInputStream to load properties from both relative path and absolute path
我写了一个供他人使用的组件。 组件通过读取属性文件进行自我配置。 属性文件的路径可以由组件的用户指定。 如果指定了路径,则可以使用FileInputStream
从绝对路径加载那些属性文件,如下所示:
Properties prop = new Properties();
InputStream input = new
FileInputStream("C:\\me\\prop\\sample.properties");
prop.load(input);
我可以读取项目的src\\main\\resources\\properties
文件夹中存在的src\\main\\resources\\properties
文件,如下所示:
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(properties\sample.properties));
这些属性嵌入在我的jar中,位于myjar.jar\\properties\\sample.properties
我可以使用FileInputStream
来从相对路径中读取属性,以便在属性加载器类中没有两种不同的方法吗?
您可以使用相对路径,但是它将相对于Java应用程序的工作文件夹。 在您的IDE(fe Eclipse)中,您可以编写:
new FileInputStream("src/main/resources/properties/sample.properties");
因为工作文件夹是项目的根文件夹。
找不到嵌入在jar中的文件。
如果您要求一个File对象,则可以指向一个外部文件或一个嵌入式资源:
File resource=new File(Ff.class.getResource("/org/json/CDL.class").getFile());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.