【发布时间】:2016-09-26 00:30:32
【问题描述】:
我写了下面的Java代码,
try {
String str = "";
Hashtable< String, String> table = new Hashtable< String, String>();
fis = new FileInputStream("C:\\Users\\Dave\\Desktop\\station.txt");// FileInputStream
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
String str1 = "012649-99999";
String str2 = "012650-99999";
while ((str = br.readLine()) != null) {
String[] record = str.split("\t");
table.put(record[0], record[1]);
}
String stationName1 = table.get(str1);
String stationName2 = table.get(str2);
} catch(...)
station.txt的内容如下:
012649-99999 SIHCCAJAVRI
012650-99999 TRNSET-HANSMOEN
当我运行程序时,stationName1 始终为空,而 stationName2 可以得到值012650-99999。谁能告诉我为什么会这样?提前谢谢!
@matt:是的,没错,当我将编码从“UTF-8”更改为“ANSI”时,它起作用了,stationName1 可以获取值,但是为什么“UTF-8”不适用于这种情况?我总是使用这种格式。
【问题讨论】:
-
你应该为一件事使用 HashMap。填充地图时如何打印记录 [0] 和记录 [1]。确保里面发生的事情是你认为的那样。
-
1) 使用
HashMap<String, String>。 2) 编程到interface所以Map<X,Y> = new HashMap<>()。 3) 你为什么不打印Map的内容来看看里面有什么?您可能需要trim()。 -
我可以确定record[0]和record[1]是我想的和我想要的,我已经打印到控制台了。
-
如果它打印出你想要的东西,那么你的错误就在其他地方。您还可以检查
record[0].equals(str2);它应该等于这些输入。否则,您已经遗漏了太多问题,没有人可以帮助您。你在哪里检查 null? -
根据您的编辑,听起来您的文件没有正确分成几行。您可能需要检查文件编码/行尾。
标签: java regex string split hashmap