13

Java怎么从这四个位置读取配置文件Properties(普通文件系统-classpath-jar-URL)

 4 years ago
source link: https://www.pkslow.com/archives/java-load-properties
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

1 简介

读取文件内容是 Java 常规操作,特别是读取配置文件,本文将介绍四种读取配置文件(Properties格式为例)的情况,分别是从普通文件系统、classpath、jar包内、网络资源 URL

2 四种位置

通过四个小示例来展示,先准备配置文件 pkslow.properties 如下:

name=pkslow
site=www.pkslow.com

(1)普通文件系统

这里说的普通文件系统就是我们平时放文件的目录,如 /opt/app/pkslow.properties ,或者是 C:\pkslow.properties 等。直接用Java读取文件流,然后载入配置。代码如下:

Properties p1 = new Properties();
String filePath = "/Users/xxx/pkslow.properties";
p1.load(new FileInputStream(filePath));

(2)classpath

Classpath 是经常会用到的位置,一般使用 Class 类的 getResourceAsStream 方法来载入文件流。

Properties p2 = new Properties();
p2.load(ReadPropertiesFile.class.getResourceAsStream("/pkslow.properties"));

这个例子里,配置文件是放在了 resources 目录下, src/main/resources/pkslow.properties

(3)jar包内

有的时候,我们需要读取第三方库jar包内的配置文件,就需要把该jar包加载进来,也是通过 Class 类的 getResourceAsStream 方法来读取,代码如下:

Properties p3 = new Properties();
p3.load(ReadPropertiesFile.class.getResourceAsStream("/com/pkslow/basic/pkslow.properties"));

这里的配置文件放在了 package com.pkslow.basic 下面。

(4)网络资源URL

有些文件不在本地,需要通过从网络 URL 加载资源,比如一些通过网络共享的配置文件。这种情况要使用 URLConnection 来建立连接,然后读取文件流:

URL url = new URL("https://pkslow.com/pkslow.properties");
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
Properties p4 = new Properties();
p4.load(inputStream);
inputStream.close();

3 总结

本文虽然讲的是读取 Properties 文件,但其它文件也是类似的。

欢迎访问 南瓜慢说 www.pkslow.com 获取更多精彩文章!

欢迎关注微信公众号< 南瓜慢说 >,将持续为你更新...

ENvAvm2.jpg!web

多读书,多分享;多写作,多整理。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK