gpt4 book ai didi

java - 从文件中读取文本行

转载 作者:行者123 更新时间:2023-11-30 01:40:54 32 4
gpt4 key购买 nike

我有一个包含 5 个客户(每行 1 个)的文本文件,客户 1、客户 2、客户 3、客户 4 和客户 5。使用以下代码,它可以完美读取 5 行文本;


import java.io.*;

public class CustomerIO {

public void method () {

try (BufferedReader br = new BufferedReader(new FileReader(new File ("Customers.txt")))) {
int numberOfLines = readLines();
String [] text = new String [numberOfLines];

for (int i = 0; i < numberOfLines; i++) {
text[i] = br.readLine();
}

for (int i = 0; i < numberOfLines; i++) {
System.out.println(text[i]);
}
} catch (Exception e) {
e.printStackTrace();
}


private int readLines() {

try (BufferedReader br = new BufferedReader(new FileReader(new File ("Customers.txt")))) {

while ((line = br.readLine()) != null) {
numberOfLines++;
}

} catch (Exception e) {
e.printStackTrace();
}
return numberOfLines;
}
}

但是,当我更改为以下内容时,输出为:Customer 2, Customer 4, null


import java.io.*;

public class CustomerIO {

String line;
int numberOfLines = 0;

public void method () {

try (BufferedReader br = new BufferedReader(new FileReader(new File ("Customers.txt")))) {

while (br.readLine() != null) {
System.out.println(br.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}


}

private int readLines() {

try (BufferedReader br = new BufferedReader(new FileReader(new File ("Customers.txt")))) {

while ((line = br.readLine()) != null) {
numberOfLines++;
}

} catch (Exception e) {
e.printStackTrace();
}
return numberOfLines;
}
}

main方法包含在下面的runner.class文件中

public class Runner {

public static void main(String[] args) {

CustomerIO cus = new CustomerIO ();
cus.method();
}
}

你能帮我理解为什么会发生这种情况吗?我想在正确读取时将客户读入数组列表,而不是使用字符串 []。

谢谢

最佳答案

问题是您为每个循环调用 readline 两次。

这是您的错误代码:

while (br.readLine() != null) {
System.out.println(br.readLine());

一个可行的解决方案可能是:

String line = br.readline();
while (line != null) {
System.out.println(line);
line = br.readline()
}

关于java - 从文件中读取文本行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60048053/

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