gpt4 book ai didi

java - Java读取文件,输出第一个逗号分隔的字符串

转载 作者:行者123 更新时间:2023-11-29 09:37:36 26 4
gpt4 key购买 nike

我想使用分隔符“,”提取文件中的第一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com