简体   繁体   中英

How can I read lines from a inputted file and then store the most recently read lines in an array?

I am trying to create a program that takes an inputted text file and reads the lines one by one. It then needs to store the most recently read lines (the number of lines depends on the parameter lines) in an array and then I need to print the lines using PrintWriter.

I started the first part but I'm not sure if I have the right idea. If anyone can help me on the second part as well that would be very appreciated!

public void RecentLines(Reader in, Writer out, int  lines) throws IOException {

BufferedReader r3ader = new BufferedReader(in);
String str;

    while((str = r3ader.readLine()) != null){
        String[] arr = str.split(" ");

        for( int i =0; i < lines; i++){
            arr[i] = r3ader.readLine();
        }
    }

EDIT

the full question is this:

Create a program which reads lines from IN, one line at the time until the end. Your method must maintain an internal buffer that stores the most recently read lines (this might be best done using an array). Once the method reaches the end of the file, it should print the lines stored in the internal buffer into out, probably best done by creating a PrintWriter to decorate this Writer. (Except for your debugging purposes during the development stage, this method should not print anything to System.out.)

Try this one:

public void RecentLines(Reader in, Writer out, int  lines) throws IOException {

BufferedReader r3ader = new BufferedReader(in);
String str;
int i=0;
String[] lineArray = new String[lines];

    while((str = r3ader.readLine()) != null){
         lines[i%lines] = str;
         i++; 
         if(!r3ader.hasNextLine()){
             break;
         } 
    }

sounds like a task for data structures. Queue seems to be the best fit for a given task.

public void RecentLines(Reader in, Writer out, int  lines) throws IOException {

    BufferedReader r3ader = new BufferedReader(in);
    BufferedWriter wout = new BufferedWriter(out);
    String str;
    Queue<String> content = new LinkedList<String>();
    int i = 0;
    while ((str = r3ader.readLine()) != null) {
        if (i >= lines) {
            content.remove();
        }
        content.add(str);
        i++;
    }
    wout.write(String.valueOf(content));
}

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