有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

集合如何一次只读取n行并以反向java打印

我的目标是一次只从文本文件中读取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++;

    }



}

共 (1) 个答案

  1. # 1 楼答案

    好的,第一件事

    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
        }
    }