所以我正在创建可以访问给定文件并从中保存/读取的文件读取器/写入器。我在从文件读取时遇到问题。内容是整数,字符串和双由“|”分隔分隔符。我正在使用StringTokenizer来分隔令牌并将它们保存到每个单独的变量中,但是当我读取整数时,我得到一个NumberFormatException,即使该字符串只包含一个int。
以下是代码:
FileReader fr = new FileReader(filename);
BufferedReader buff = new BufferedReader(fr);
String line;
while ((line = buff.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, "|");
while (st.hasMoreElements()) {
int Id = Integer.parseInt(st.nextToken());
String Name = st.nextToken();
double cordX = Double.parseDouble(st.nextToken());
double cordY = Double.parseDouble(st.nextToken());
}
}
文件的示例行:
8502113|Aarau|47.391355|8.051251
错误:
java.lang.NumberFormatException: For input string: "8502113"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at storage.FileUtilities.readCitiesFromFile(FileUtilities.java:63)
at basics.Test.main(Test.java:16)
我在这里遗漏了什么吗? StringTokenizer是否以某种我不知道的方式篡改字符串?
编辑:以下是创建文件的代码:
FileWriter fw = new FileWriter(filename, !overwrite); // For FileWriter true = append, false = overwrite, so we flip the value.
BufferedWriter buff = new BufferedWriter(fw);
String coordConvertor;
for (int i = 0; i <= cities.size() - 1; i++) {
buff.write(Integer.toString(cities.get(i).getId()));
buff.write("|");
buff.write(cities.get(i).getName());
buff.write("|");
coordConvertor = Double.toString(cities.get(i).getCoord().getX());
buff.write(coordConvertor);
buff.write("|");
coordConvertor = Double.toString(cities.get(i).getCoord().getY());
buff.write(coordConvertor);
buff.newLine();
答案 0 :(得分:3)
使用 st.nextToken()检索的字符串中有隐藏的unicode字符。 请使用此代码将其删除
\vendor\friendsofsymfony\user-bundle