如果您对具有特殊含义的前导选项卡感到满意,我想我会像这样格式化我的文件:
key1
value1-a
value1-b
key2
value2-a
key3
value3-a
value3-b
value3-c
前导制表符表示字符串是一个值(不是一个键)。
然后解析器:
public class MapBuilder
{
private final Map<String, Collection<String>> map;
private Collection<String> col;
public MapBuilder()
{
map = new LinkedHashMap<String, Collection<String>>();
}
public Map<String, Collection<String>> getMap()
{
return map;
}
public void addLine(String line)
{
if (line.length() > 0)
{
if (line.charAt(0) == '\t')
{
if (col == null)
{
throw new IllegalArgumentException(
"No key specified");
}
col.add(line.substring(1));
}
else
{
col = new ArrayList<String>();
map.put(line, col);
}
}
}
public static Map<String, Collection<String>> getMap(File file,
Charset charset) throws IOException
{
MapBuilder mb = new MapBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(file), charset));
try
{
String line;
while ((line = br.readLine()) != null)
{
mb.addLine(line);
}
return mb.getMap();
}
finally
{
try
{
br.close();
}
catch (Throwable t)
{
t.printStackTrace();
}
}
}
}
用法:
Map<String, Collection<String>> myMap = MapBuilder.getMap(
new File("C:/myfile.txt"), Charset.forName("US-ASCII"));