gpt4 book ai didi

java - 从文本文件中读取行范围

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

我有一个非常大的文本文件,如下所示:

0  239.0 -13.0 0
1 240.0 -13.0 33
2 241.0 -13.0 34
3 242.0 -13.0 44
4 243.0 -13.0 45
5 244.0 -13.0 74
6 245.0 -13.0 74
7 246.0 -13.0 79
8 247.0 -13.0 79
9 248.0 -13.0 113
10 249.0 -13.0 113
11 250.0 -13.0 120
12 251.0 -13.0 120
13 252.0 -13.0 153
14 253.0 -13.0 153
15 254.0 -13.0 160
16 255.0 -13.0 160
17 256.0 -13.0 194
18 257.0 -13.0 195
19 258.0 -13.0 199
20 259.0 -13.0 200
21 260.0 -13.0 232
22 261.0 -13.0 232
23 262.0 -13.0 239
...
...

每一行的最后一个条目是一个时间戳。现在我想实现一个名为 read(int timestamp, int range) 的方法,它以高效的方式从这个文本文件中返回一系列行。例如,如果我调用 read(10250,100),我想查找时间戳为 10250 的行(如果存在,则取最近的行)并返回 100 行 before 时间戳行,包含时间戳本身的行以及字符串数组中时间戳行之后的 100 行。

这是我目前对 read(int timestamp, int range) 的实现:

public static void read(int timestamp,int range) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("LOG_TEST"));
String line;
int currTimestamp;
while ((line = br.readLine()) != null) {
currTimestamp = Integer.parseInt(line.split("\\s+")[3]);
if (currTimestamp >= timestamp) {
for(int i = 0; i<range;i++){
System.out.println(br.readLine());
}
break;
}
}
br.close();
}

问题是这个实现只打印出时间戳之后的 100 行。我不知道如何包括之前的 100 行。因为我不知道时间戳行在哪一行,所以我需要以某种方式读取“向后”以获取之前的 100 行。我怎样才能有效地实现它?亲切的问候

最佳答案

我会使用 CircularFifoQueue具有固定大小的 range,例如100.引用它的add方法:

Adds the given element to this queue. If the queue is full, the least recently added element is discarded so that a new element can be inserted.

这样,您只在内存中保留 range 行,而不是之前的所有行。

您可以从here 下载jar。 .

它还提供了一个 get(int index) 方法,您可以使用该方法按您希望的顺序打印行,但我认为您不需要它,因为迭代器返回按插入顺序排列的元素。所以,这是我的建议:

public static void read(int timestamp,int range) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("LOG_TEST"));
String line;
CircularFifoQueue<String> prevLines = new CircularFifoQueue<>(range);
int currTimestamp;
while ((line = br.readLine()) != null) {
currTimestamp = Integer.parseInt(line.split("\\s+")[3]);
if (currTimestamp >= timestamp) {
for (String prevLine : prevLines) { //prints the range previous lines
System.out.println(prevLine);
}
System.out.println(line); //prints the current line
for(int i = 0; i<range;i++){ //prints the following range lines
System.out.println(br.readLine());
}
break;
} else {
prevLines.add(line);
}
}
br.close();
}

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

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