package com.properties;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Myproperties {
public static void main(String[] args) throws IOException {
//IO流的寻址
//src内
InputStream in2 = new FileInputStream("src/liudonghe.properties");
//工程内
InputStream in3 = new FileInputStream("config.properties");
Properties prop2 = new Properties();
Properties prop3 = new Properties();
prop2.load(in2);
prop3.load(in3);
in3.close();
in2.close();
System.out.println("2---"+prop2.getProperty("sfwl"));
System.out.println("3---"+prop3.getProperty("wl"));
//类加载器
InputStream in4 = Myproperties.class.getResourceAsStream("/liudonghe.properties");
//InputStream in5 = Myproperties.class.getResourceAsStream("../config.properties");
Properties prop4 = new Properties();
Properties prop5 = new Properties();
prop4.load(in4);
//prop5.load(in5);
in4.close();
//in5.close();
System.out.println("4---"+prop4.getProperty("sfwl"));
//System.out.println("5---"+prop5.getProperty("wl"));
}
}
以上通过正常的文件流,和类加载器,加载,来实现对properties的加载,在原来图片加载总是出现路径不对,这里对路径进行详解。
2和3分别对,工程下的properties和类下的properties进行解析,eclipse在类下的文件,保存后会加载到对应的class文件位置
如图所示。所以,2你引用的时候需要加上src就可以了。但在。实际的项目中我们通常采用绝对路径的拼接方式。这个这里不解释了。
3就正常了,从工程开始找。前面没有加上‘/’代表相对路径,就是从工程下找,不索引物理地址。
类加载器,必须在src下,否则,会报错(5),目前我还没有找到,解决的办法。 在src下的时候,不用'/'代表相对位置,从本个类开始找,带'/'代表绝对位置,从src开始找。