解析一个int时出现NumberFormatException [英] NumberFormatException while parsing an int
问题描述
所以我正在制作可以访问给定文件并从中保存/读取文件的文件读取器/写入器.从文件中读取文件时遇到了问题.内容是整数,字符串和由"|"分隔的双精度定界符.我正在使用StringTokenizer来分隔标记并将它们保存到每个单独的变量中,但是当我读取整数时,即使字符串仅包含一个整数,我也会得到NumberFormatException.
So I am making file reader/writer that can access a given file and save/read from it.I am having a problem while reading from the file. The contents are integers, string and double separated by "|" delimiters. I am using StringTokenizer to separate the tokens and save them to each individual variable but when I am reading the integers I get a NumberFormatException even though the string contains only an 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是否以我不知道的某种方式篡改字符串?
Am I missing something here? Is StringTokenizer tampering the string in some kind of way that I don't know?
以下是创建文件的代码:
Here is the code that creates the file:
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();
推荐答案
通过 st.nextToken()检索到的 String 中有隐藏的Unicode字符 . 请改用此代码删除它们
There are hidden unicode characters in the String your retrieved with st.nextToken(). Use this code instead to remove them
int Id = Integer.parseInt(st.nextToken().replaceAll("\\p{C}", ""));
String Name = st.nextToken().replaceAll("\\p{C}", "");
double cordX = Double.parseDouble(st.nextToken().replaceAll("\\p{C}", ""));
double cordY = Double.parseDouble(st.nextToken().replaceAll("\\p{C}", ""));
这篇关于解析一个int时出现NumberFormatException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!