我正在尝试解析数据文件。该代码已成功地用于我的其他datfiles。但是,我现在遇到一个错误。这些数据文件旨在使计算机尝试读取第一个空格。我如何跳过这个空间?
String line = br.readLine();
while (line != null) {
String[] parts = line.split(" ");
if (linecounter != 0)
{
for (int j=0; j<parts.length; j++)
{
if (j==parts.length-1)
truepartition.add(Integer.parseInt(parts[j]));
else
{
tempvals.add(Double.parseDouble(parts[j]));
numbers.add(Double.parseDouble(parts[j]));
}
}
Points.add(tempvals);
tempvals = new ArrayList<Double>();
}
else
{
//Initialize variables with values in the first line
// Reads each elements in the text file into the program 1 by 1
for (int i=0; i<parts.length; i++) {
if (i==0)
numofpoints = Integer.parseInt(parts[i]);
else if (i==1)
dim = Integer.parseInt(parts[i]) - 1;
else if (i==2)
numofclus = Integer.parseInt(parts[i]);
}
}
linecounter++;
line = br.readLine();
}
Data File
75 3 4
4 53 0
5 63 0
10 59 0
此数字格式错误即将出现,因为您无法在基数10中设置空格字符。我可以看到您的输入中还有许多额外的空格,split(“”)不能使用。
所以用正则表达式替换普通的空格。使用下面的代码,它将处理您输入中多余的空格。
String[] parts = line.trim().split("\\s+");
您是否考虑过使用Scanner类。跳过空间并有助于解析文件。
例如:
try {
inp = new Scanner(new File("path/to/dataFile"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(inp.hasNext()) {
int value = inp.nextInt();
System.out.println(value);
}
inp.close();