问题
I want to read lines from a file into a Set or List. Is there a standard utility for doing this?
If these lines are of the form [key]=[value] I can do:
Properties properties = new Properties();
properties.load(new FileInputStream(file));
The values are single entries, one per line, each value becomes an entry in the Set/List
I know it can be done with LineReader, InputStreams and plenty of boilerplate but I'm looking to avoid this.
回答1:
yes, the Properties class itself provides accessor methods for convertions:
public Set<Map.Entry> entrySet()
Returns a KeySet view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
public Set<K> keySet()
Returns a KeySet view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
in alternative you can Enumerate the property using elements()
回答2:
If, by standard utility, you mean 3rd-party library, then my answer is: almost!
The Apache Commons is worthy of being a part of almost any Java application. Using IOUtils from the Apache Commons, you can achieve what you describe by doing this:
final List list = IOUtils.readLines(new FileInputStream(file));
Set<String> set = new HashSet<String>(list);
The set will contain each line from the file.
Note: IOUtils is not generics-aware, so this code fragment will give a compile warning.
来源:https://stackoverflow.com/questions/1091449/is-there-an-equivalent-of-java-util-properties-for-sets