Java 程序经常要读取配置文件(properties)、图片(jpg)、文本文件(txt、csv),我们可以使用 上次所讲的 InputStream 实现。
public static void main(String[] args) throws Exception {
String path = "D:\\config.properties";
byte[] config = new byte[1024];
try (InputStream inputStream = new FileInputStream(path)){
while (inputStream.read(config) != -1) {
System.out.println(new String(config, "utf-8"));
}
}
}
读取classpath
java 程序经常是部署在 Linux 上的,必然不可能使用 "D:" 这种盘符路径。总不能在开发的时候用 windows 路径,发布到 Linux 的时候注释掉吧?最终,将配置文件放在 java 程序的 resources 下
- 使用 class 处理
class 的 getResourceAsStream() 方法可以返回一个 InputStream。
publ