简体   繁体   中英

reversing order of lines in txt file every 'x' number of lines - JAVA

so i have an input txt file where i have to take the first 50 lines and reverse it's order so that the file will start with the 50th line, then the 49th, until the 1st, then continues with the 100th line followed by the 99th, and so on...

but i can only store at most 50 elements. i can't store more than that. the code i've written so far only grabs the first 50 lines and reverses them, but i dont know how to make it continue on.

this is what i have so far:

ArrayList<String> al = new ArrayList<String>();
int running = 0;

while(running == 0) {
    for (String line = r.readLine(); line != null; line = r.readLine()) {
        if(al.size() <50 ) {
            al.add(line);
        }
    }
    Collections.reverse(al);
    for (String text : al) {
        w.println(text);
    }

    if(al.size() < 50) {
        break;
    }
    al.clear();
}

idk why my while loop won't keep running, im only getting the first 50 lines reversed in my output file.

This:

    for (String line = r.readLine(); line != null; line = r.readLine()) {
        if(al.size() <50 ) {
            al.add(line);
        }
    }

reads all the lines in the file, stores the first fifty in al , and discards the rest. After you then process the results of al , there's nothing more for your program to do: it's read the whole file.

There's a great blog post on how to debug small programs, that I highly recommend: http://ericlippert.com/2014/03/05/how-to-debug-small-programs/

And in your specific case, I suggest breaking your program into functions. One of those functions will be "read up to n lines, and return them in an array-list". This sort of structure makes it easier to reason about each part of the program.

Your initial loop:

for (String line = r.readLine(); line != null; line = r.readLine()) {
    if(al.size() <50 ) {
        al.add(line);
    }
}

Continues to read lines after you've filled al through to the end of the file - it just doesn't put them in the list.

You most likely need something like:

for (String line = r.readLine(); line != null; line = r.readLine()) {
    if (al.size() == 50)
        outputReverseLines();
    al.add(line);
}
outputReverseLines();

Where outputReverseLines is a method that reverses, prints and clears the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM