我正在尝试加载属性文件并读取属性文件中给定键的值。属性文件如下所示:
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
我尝试调试,对于 props.load 处的第一个打印语句将所有 3 个属性加载到 props 中,但对于第二个和第三个打印语句 props.load 将零个属性加载到 props 中。
最佳答案
提供的流位于 props.load
之后的结束位置,因此无法再读取任何内容。
您可以在每次调用之前重新打开流,或者(更好)只加载一次属性并重用 Properties
实例:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
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"));
// Variant 1
stream = new FileInputStream(new File(path));
System.out.println(test.getValue(stream, "A"));
stream = new FileInputStream(new File(path));
System.out.println(test.getValue(stream, "B"));
stream = new FileInputStream(new File(path));
System.out.println(test.getValue(stream, "C"));
// Variant 2
stream = new FileInputStream(new File(path));
Properties props = new Properties();
props.load(stream);
System.out.println(props.getProperty("A"));
System.out.println(props.getProperty("B"));
System.out.println(props.getProperty("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;
}
}
作为旁注,您应该使用 try-with-resources
声明以确保您的流随后关闭:
Properties props = new Properties();
try (InputStream stream = new FileInputStream(new File(path));) {
props.load(stream);
}
System.out.println(props.getProperty("A"));
System.out.println(props.getProperty("B"));
System.out.println(props.getProperty("C"));
关于java属性不会再次加载同一流的输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46062176/