我想使用分隔符“,”提取文件中的第一个 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 还提到的,不要在 while
循环中再次read = in.readLine();
因为这样做所以你跳过了一行。
while ((read = in.readLine()) != null) {
String[] splited = read.split(",");
System.out.println(splited[0]);
}
关于java - Java读取文件,输出第一个逗号分隔的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31052825/