【发布时间】:2017-02-03 02:32:59
【问题描述】:
我有一个如下所示的文本文件:
A
Apple
B
Bat
C
Cat
......
我需要读取这个文本文件并将其保存在一个 HashMap 中,其中奇数行是键,下面的偶数行是值。例如,(A,苹果)。我已经尝试使用以下代码,它不起作用。有人可以给我一些提示或建议吗?
private HashMap<String, String> newHashMap = new HashMap<String, String>();
Charset charset = Charset.forName("US-ASCII");
Path path = Paths.get("file_location");
try (BufferedReader reader = Files.newBufferedReader(path, charset)) {
int lineCount = 0;
String key;
String value;
String line = reader.readLine();
while(line != null) {
line = reader.readLine();
if (lineCount % 2 == 1)
{
key = reader.readLine() ;
}
else if( lines % 2 == 0)
{
value = reader.readLine();
}
lineCount++;
newHashMap.put(key, value);
}
【问题讨论】:
-
"...it doesn't work"-- 告诉我们很少使用。请在此处帮助我们 - 向我们提供帮助调试此问题所需的信息。 -
把
line = reader.readLine();放在循环的末尾。 -
为什么不每个循环只有 2 个
readLines,并避免所有的模数? -
只看两行,不要乱用
lineCount -
并且不要在 if 语句中继续阅读。
line中已有值,请使用它。