Raghu
Raghu

Reputation: 1324

How to read a file continuously?

I want to read a file continuously , I mean if I found an end of file , I want to read it again from first. So I am reseting the stream but it is not working. Here is my code.

 br = new BufferedReader(new FileReader("E:\\Abc.txt"));
        while(true)
        {

            sCurrentLine = br.readLine();
            if(sCurrentLine!=null)
                System.out.println(sCurrentLine);
            else
                br.reset();

        } 

can anyone help me in this please.

Upvotes: 1

Views: 1748

Answers (3)

ColdFridge
ColdFridge

Reputation: 39

br = new BufferedReader(new FileReader("E:\\Abc.txt"));
while(true) {
     sCurrentLine = br.readLine();
     if(sCurrentLine!=null) {
          System.out.println(sCurrentLine);
     } else {
          br.close();
          br = new BufferedReader(new FileReader("E:\\Abc.txt"));
     }
}

So it will restart with a fresh BufferedReader :)

Upvotes: 2

Raceimaztion
Raceimaztion

Reputation: 9634

Your best bet might be to recreate the BufferedReader once readLine() returns null.

For example:

String filename = "[filename]";
BufferedReader reader = new BufferedReader(new FileReader(filename));

while (true) {
    String line = reader.readLine();
    if (line != null)
        // Use line
    else {
        reader.close();
        reader = new BufferedReader(new FileReader(filename));
    }
}

This has the advantage of always reading straight from the file without storing too much of it in memory at a time, which could be a concern if, as you've said, it contains five thousand lines.

Upvotes: 1

Ian2thedv
Ian2thedv

Reputation: 2701

Add br.mark(100); after initialising br

Marks the present position in the stream. Subsequent calls to reset()
will attempt to reposition the stream to this point.

On parameter readAheadLimit:

readAheadLimit Limit on the number of characters that may be read while still preserving the mark. An attempt to reset the stream after reading characters up to this limit or beyond may fail. A limit value larger than the size of the input buffer will cause a new buffer to be allocated whose size is no smaller than limit. Therefore large values should be used with care.

The following code will continuously print the contents of the file /home/user/temp/reader.test

    BufferedReader br = new BufferedReader(new FileReader("/home/user/temp/reader.test"));
    String sCurrentLine;

    br.mark(100);
    while(true)
    {
        sCurrentLine = br.readLine();
        if(sCurrentLine!=null)
            System.out.println(sCurrentLine);
        else
            br.reset();
    } 

Upvotes: 0

Related Questions