【发布时间】:2017-03-24 17:40:52
【问题描述】:
我需要读取 csv 文件。该文件有一些不同的类型,如int、float、String、char。我怎么知道是什么类型?
我确实为它编写了一些代码,但我的问题是浮点数。在我的计算机中,java 说“7.9”不是浮点数,但“7,9”是。
但在某些计算机上,“7.9”是一个浮点数。我该如何解决这个问题?
public static void Read(String filename) throws FileNotFoundException{
File file = new File(filename);
Scanner scanner1 = new Scanner(file);
String line ;
Scanner scanner;
int a;
float f;
String temp ;
while(scanner1.hasNextLine()){
line = scanner1.nextLine();
scanner = new Scanner(line);
scanner.useDelimiter(",|\\n");
while (scanner.hasNext()){
if (scanner.hasNextInt()){
a = scanner.nextInt();
System.err.printf("Int :%d",a);
}
else if(scanner.hasNextFloat()){
f = scanner.nextFloat();
System.err.printf("flt :%f",f);
}
else {
temp = scanner.next();
if(temp.length() == 1)
System.err.printf("char:%s",temp);
else
System.err.printf("string:%s",temp);
}
}
System.err.printf("\n");
scanner.close();
}
}
【问题讨论】:
-
注意:这将无法正确读取包含逗号的字符串的 CSV 文件。即)
1,2,3,"A,B,C"包含 4 个值,最后一个是带有 2 个逗号的字符串。您应该使用适当的 CSV 库。
标签: java floating-point