gpt4 book ai didi

java - 尝试从文件中读取数据(文件每两行包含换行符)

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

首先,这是数据文件的样子

5165168416516988798484984984984984
9898798798798

1556516846516518498
51688484979789798798798491

我需要阅读该换行符之前的两行(我可以做到),然后继续两两阅读,直到文件结束。配对数量保证为偶数,因此最后不会出现孤行。我的问题是尝试读取前两行以外的文件。

code
try {
Scanner input = new Scanner (file);
while (input.hasNextLine()) {
String number1 = input.nextLine();
String number2 = input.nextLine();

System.out.println("String: " + number1);
System.out.println("String: " + number2);

System.out.println(number1 + " " + number2);

number1= input.nextLine();
number2= input.nextLine();
}
}

是我到目前为止所做的。它仅在根本没有换行符的情况下才有效,但它仍然会在最后抛出一个异常(“找不到行”)。

一旦在文件中找到第一个中断,就会发生此异常。如何使整个文件以我想要的方式读取? (捕获这两行,对它们做点什么。捕获接下来的两行,做点什么……一直到最后)

最佳答案

好的。让我们试试。

try {
Scanner input = new Scanner (file);

// input.hasNextLine() checks if there are more lines that can be read from
// the file. If there is a line, hasNextLine() will return true, and the code
// inside the while block will be executed.
// Then execution will come back here to perform the check again. This
// goes on until there are no more lines to consume.
while (input.hasNextLine()) {

// We are going to read two numbers from file.
// Ideally, we should check if there a line available before reading
// each of these lines. But since you confirm that the file will
// always have multiple number of triplets containing two lines
// with numbers, followed by a blank line, we are not going to
// call input.hasNextLine() here.
String number1 = input.nextLine();
String number2 = input.nextLine();

// Now, two numbers are read, read the next (empty) line to a variable
// but we will not use it anywhere.
String emptyLine = input.nextLine();
// ...or we could read it, but just discard it without assigning it to a variable
// input.nextLine();

// Print what we read to the output, like a boss.
System.out.println("String: " + number1);
System.out.println("String: " + number2);
System.out.println(number1 + " " + number2);

// This is not needed here (see below to understand why):
//number1= input.nextLine();
//number2= input.nextLine();

// after the following brace (}), execution will go back to the start
// of the while loop. and if there are more lines to be read, code
// inside while loop will be executed again.
}
}

希望这能解决问题。

警告:要使此代码无误运行,您的输入文件中最后一个数字对后必须包含一个空行。否则它会抛出一个 NoSuchElementException

关于java - 尝试从文件中读取数据(文件每两行包含换行符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24844298/

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