当我尝试将字符串转换为double时,我正在使用NumberFormatException。似乎我有正确的方法去做,但异常仍然出现。这真的让我很生气,因为我上周一直在努力。这是我正在尝试做的事情:
String csvFile="N:/Downloads/Chrome Downloads/GeoIPCountryWhois.csv";
BufferedReader br=null;
String line="";
String cvspl=",";
try{
for(int i=0;i<5000;i++)
{
//System.out.println("I'm here in retriving IP");
br=new BufferedReader(new FileReader(csvFile));
while ((line=br.readLine())!=null){
String[] country=line.split(cvspl);
l.add(country[0]);
double a = Double.parseDouble(country[2]);
double b = Double.parseDouble(country[3]);
IpParameters p = new IpParameters(a, b);
IP.put(country[0], p);
}
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}finally{
if (br !=null){
try{
br.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
} }
我正在成功检索文件中的数字。当我打印国家[2]时,它显示存储在该索引中的值。
答案 0 :(得分:2)
我找到了这个文件https://raw.githubusercontent.com/alecthomas/geoip/master/GeoIPCountryWhois.csv (如果它与您的工作文件类似)并使用以下两行进行测试:
"1.0.0.0","1.0.0.255","16777216","16777471","AU","Australia"
"1.0.1.0","1.0.3.255","16777472","16778239","CN","China"
并且错误是
Exception in thread "main" java.lang.NumberFormatException: For input string: ""16777216""
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at Test.main(Test.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
我的代码有效:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
/**
* Created by mojtab23 on 8/1/16.
*/
public class Test {
public static void main(String[] args) {
BufferedReader br = null;
String line = "";
String cvspl = ",";
try {
//System.out.println("I'm here in retriving IP");
br = new BufferedReader(new StringReader("\"1.0.0.0\",\"1.0.0.255\",\"16777216\",\"16777471\",\"AU\",\"Australia\"\n" +
"\"1.0.1.0\",\"1.0.3.255\",\"16777472\",\"16778239\",\"CN\",\"China\""));
while ((line = br.readLine()) != null) {
String[] country = line.split(cvspl);
// l.add(country[0]);
double a = Double.parseDouble(country[2].replaceAll("\"", ""));
double b = Double.parseDouble(country[3].replaceAll("\"", ""));
// IpParameters p = new IpParameters(a, b);
System.out.println("IP: " + country[0]);
System.out.println(a + " ," + b);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}