有没有办法读取一行和下一行,遍历 Java 中的 .txt 文件?
Is there a way to read one line and the next one, iterating over a .txt file in Java?
我想使用 BufferReader 读取 .txt 文件的一行。但我的问题是我需要一起阅读一行和下一行,然后转到下一行并再次阅读下一行。这是一个例子:
A
B
C
D
我需要阅读 A 和 B(和处理),然后是 B 和 C(处理),然后是 C 和 D。
我是否需要创建一个数组来存储每一对然后进行处理?或者我可以在遍历文件时进行处理吗?我目前正在这样做:
while (file = in.readLine() != null) {
String[] data = file.split(",");
String source = data[0];
file = in.readLine();
String destination = data[0];
}
这里的目标是将之前的目的地作为下一个来源。
但是当我的 while 循环进入下一行时,我不会跳过一个字母吗?
感谢您的关注!
您可以尝试这样的操作:
String a = in.readLine();
if (a == null) {
return;
}
for (String b; (b = in.readLine()) != null; a = b) {
// do smth
}
说不定Stream管道的reduce操作对你也有帮助。例如,如果您想将所有行连接在一起:
Optional<String> reduce = in.lines().reduce("", (a,b) -> a+b);
if (reduce.isPresent()) {
// ..
} else {
// ...
}
我会使用两个元素的 String
数组作为“缓冲区”。
String[] buffer = new String[2];
try (FileReader fr = new FileReader("path-to-your-file");
BufferedReader br = new BufferedReader(fr)) {
String line = br.readLine();
while (line != null) {
if (buffer[0] == null) {
buffer[0] = line;
}
else if (buffer[1] == null) {
buffer[1] = line;
}
else {
// Do whatever to the contents of 'buffer'
buffer[0] = buffer[1];
buffer[1] = line;
}
line = br.readLine();
}
// Do whatever to the contents of 'buffer'
}
catch (IOException xIo) {
xIo.printStackTrace();
}
当你退出while
循环时,文件的最后两行还没有处理,所以你需要在退出循环后进行最后一次处理。
我想使用 BufferReader 读取 .txt 文件的一行。但我的问题是我需要一起阅读一行和下一行,然后转到下一行并再次阅读下一行。这是一个例子:
A
B
C
D
我需要阅读 A 和 B(和处理),然后是 B 和 C(处理),然后是 C 和 D。
我是否需要创建一个数组来存储每一对然后进行处理?或者我可以在遍历文件时进行处理吗?我目前正在这样做:
while (file = in.readLine() != null) {
String[] data = file.split(",");
String source = data[0];
file = in.readLine();
String destination = data[0];
}
这里的目标是将之前的目的地作为下一个来源。 但是当我的 while 循环进入下一行时,我不会跳过一个字母吗?
感谢您的关注!
您可以尝试这样的操作:
String a = in.readLine();
if (a == null) {
return;
}
for (String b; (b = in.readLine()) != null; a = b) {
// do smth
}
说不定Stream管道的reduce操作对你也有帮助。例如,如果您想将所有行连接在一起:
Optional<String> reduce = in.lines().reduce("", (a,b) -> a+b);
if (reduce.isPresent()) {
// ..
} else {
// ...
}
我会使用两个元素的 String
数组作为“缓冲区”。
String[] buffer = new String[2];
try (FileReader fr = new FileReader("path-to-your-file");
BufferedReader br = new BufferedReader(fr)) {
String line = br.readLine();
while (line != null) {
if (buffer[0] == null) {
buffer[0] = line;
}
else if (buffer[1] == null) {
buffer[1] = line;
}
else {
// Do whatever to the contents of 'buffer'
buffer[0] = buffer[1];
buffer[1] = line;
}
line = br.readLine();
}
// Do whatever to the contents of 'buffer'
}
catch (IOException xIo) {
xIo.printStackTrace();
}
当你退出while
循环时,文件的最后两行还没有处理,所以你需要在退出循环后进行最后一次处理。