我想加载属性文件并读取属性文件中的给定键的值。属性文件看起来像:java属性不再加载输入流的相同的流再次
text.properties
A=Z
B=Y
C=X
public class TestStreams {
static String path = "test.properties";
public static void main(String[] args) throws IOException {
TestStreams test = new TestStreams();
InputStream stream = new FileInputStream(new File(path));
System.out.println(test.getValue(stream, "A"));
System.out.println(test.getValue(stream, "B"));
System.out.println(test.getValue(stream, "C"));
}
public String getValue(InputStream stream, String key) throws IOException {
Properties props = new Properties();
String value = null;
try {
props.load(stream);
value = props.getProperty(key);
} catch (IOException e) {
e.printStackTrace();
}
return value;
}
}
Output :
Z
null
null
我试图调试,为第一print语句在props.load加载所有3个属性为道具,但对于第二和第三打印语句props.load负荷为零性质为道具。
第一props.load(流)是要读取文件的全部内容为对象的属性,并击中了文件的末尾,以便为属性对象第一个的getValue将有“A”,“B”和“C” ”。由于属性对象没有被返回,所以它被垃圾回收。下一次调用getValue会创建一个新的Properties对象,但是由于流已经到达文件的末尾,所以没有剩下任何东西读入它(以后的任何调用getValue都是一样的)。 – Sticks
为什么你会这样做,而不是保存'Properties'对象? – EJP