我想使用定界符“,”提取文件中的第一个String
。
为什么此代码生成的行数大于一?
public static void main(String[] args) {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("irisAfter.txt"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.split(",");
for (int i =0; i<splited.length;i++) {
System.out.println(splited[0]);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) { e.printStackTrace(); }
}
}
最佳答案
您正在循环内打印。这就是为什么要多次打印的原因(如果这就是您要的内容)。
String[] splited = read.split(",");
System.out.println(splited[0]);
会做
编辑:正如Abishek所说,不要在
read = in.readLine();
循环内再次while
,因为这样做会跳过一行。while ((read = in.readLine()) != null) {
String[] splited = read.split(",");
System.out.println(splited[0]);
}