如何一次只读n行并反向打印java

How do I only read n lines at a time and print in reverse java

我的objective是一次只从文本文件中读取50行,以相反的顺序打印它们并且一次只在内存中存储50行。以最有效的方式。

这是我想出的代码,但输出与预期不符。我已经用 104 行的输入文件对其进行了测试。

实际输出:它打印第 50 行到第 1 行,第 101 行到第 52 行(跳过第 51 行),第 104 到 103 行(跳过第 102 行)。

预期输出:第 50 行 - 第 1 行、第 101 行 - 第 51 行、第 104-102 行。

我也不知道如何更改第一个 while 循环,使其一直运行到文件末尾,因为测试 while (r.readLine != null) 也不起作用。

public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
    Stack<String> s = new Stack<String>();
    int i = 0;
    int x = 0;


    while (x < 5) {
        for (String line = r.readLine(); line != null && i < 50; line = r.readLine()) {
            s.push(line);
            i++;
        }

        i = 0;

        while (!s.isEmpty()) {
            w.println(s.pop());

        }

        x++;

    }



}

看起来像你把

line = r.readLine()

在迭代中,检查前正在读取一行

line != null && i < 50

这导致一行被读取,而不是检查 i 是否 i<50,并且由于 i 确实小于 50,所以该行不会被压入堆栈,一旦我们被压入堆栈,我们就会忘记它在 for 块之外。

尝试在 for 块内重新标记行。如果需要,您仍然可以在 for 块中保留 line!=null 的条件。

干杯!

好的,首先是第一件事

for (String line = r.readLine(); line != null && i < 50; line = r.readLine()) 

这个for循环再读一次达到50。这是多行的主要原因。

I also don't know how to change the first while loop so it keeps going until the end of the file

这是因为你做的不对。我制作了一个模型来打印所需的行为:

public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
    Stack<String> s = new Stack<String>();
    int i = 0;
    int x = 0;
    String strLine;
    while ((strLine = r.readLine()) != null){ // Read until end of File
        s.push(strLine); // add to the Stack
        i++;
        if(i==50) // Print if is equal to 50
        {
            while (!s.isEmpty()) {
                System.out.println(s.pop());
            }
            i=0;
        }
    }

    while (!s.isEmpty()) {
        System.out.println(s.pop()); // Print the last numbers
    }
}

您可以使用 lines()BufferedReader 创建一个流,然后只取 50 个元素。 好像

List<String> lines = r.lines().limit(50).collect(toList());

然后您可以从列表中迭代并打印行;

for(int i = lines.size()-1; i >= 0; --i) {
   System.out.println(lines.get(i));
}