在某些答案中,假设从文件中读取的属性被放入Properties
(通过调用put
)的实例中,以便它们出现在文件中。虽然这通常是它的行为方式,但我看不到这种顺序的任何保证。
恕我直言:最好逐行读取文件(以保证顺序),而不是将 Properties 类用作单个属性行的解析器,最后将其存储在一些有序的 Collection 中,例如LinkedHashMap
.
这可以这样实现:
private LinkedHashMap<String, String> readPropertiesInOrderFrom(InputStream propertiesFileInputStream)
throws IOException {
if (propertiesFileInputStream == null) {
return new LinkedHashMap(0);
}
LinkedHashMap<String, String> orderedProperties = new LinkedHashMap<String, String>();
final Properties properties = new Properties(); // use only as a parser
final BufferedReader reader = new BufferedReader(new InputStreamReader(propertiesFileInputStream));
String rawLine = reader.readLine();
while (rawLine != null) {
final ByteArrayInputStream lineStream = new ByteArrayInputStream(rawLine.getBytes("ISO-8859-1"));
properties.load(lineStream); // load only one line, so there is no problem with mixing the order in which "put" method is called
final Enumeration<?> propertyNames = properties.<String>propertyNames();
if (propertyNames.hasMoreElements()) { // need to check because there can be empty or not parsable line for example
final String parsedKey = (String) propertyNames.nextElement();
final String parsedValue = properties.getProperty(parsedKey);
orderedProperties.put(parsedKey, parsedValue);
properties.clear(); // make sure next iteration of while loop does not access current property
}
rawLine = reader.readLine();
}
return orderedProperties;
}
请注意,上面发布的方法采用InputStream
之后应该关闭的方法(当然,重写它以仅将文件作为参数是没有问题的)。