BufferedReader - Freezes on 2nd read
Hello
I am trying to read from a buffered reader.
Cannot really post the code as it is for an assignment I have.
Basically i need to send text to a buffered reader, read this into a file using printWriter but also display this on the screen.
So when i do a while loop that loops until EOF is reached works fine.
the 2nd while loop that reads into a file using the same method above just freezes the program.
Do i have to open the close the bufferedReader when that read has finished ready for another read? or something as i am really struggling?
using .readLine() method
Re: BufferedReader - Freezes on 2nd read
You cannot reuse a BufferedReader like this - it has reached the end of the file and unless you use a RandomAccessFile (or some other class which allows you to reset the pointer) the file marker will remain at the end of the file (eg no second read). Not sure why you need to read the file twice...but you can just recreate the BufferedReader (be sure to close the Readers when you are done with them).
Re: BufferedReader - Freezes on 2nd read
Thanks for the quick reply: here is some of my code:
This display's it:
Code Java:
public void display()
{
String line;
try
{
line = from.readLine();
while(!line.equals("EOF"))
{
System.out.println(line);
line = from.readLine();
}
}
catch(IOException e)
{
System.out.println("Error " + e.getMessage());
}
}
This saves it:
Code Java:
private void save()
{
try
{
PrintWriter pwOutput = new PrintWriter(arg);
String line = from.readLine();
while(!line.equals("EOF"))
{
pwOutput.println(line);
line = from.readLine();
}
pwOutput.flush();
pwOutput.close();
}
catch (IOException e)
{
System.out.println("Error " + e.getMessage());
}
}
Re: BufferedReader - Freezes on 2nd read
Like I said, don't reuse the BufferedReader, and I'd also recommend not looking for "EOF" - the readLine returns null....so check for the returned string to be null. I'd recommend rewriting your code to take these into account. Depending upon what you wish to accomplish, you could read the file in once, and then use the read contents for the multiple tasks.
Re: BufferedReader - Freezes on 2nd read
thanks for the reply. need to use EOF as that what the assignment says.
Basically i need to send and receive text to a server / client. So i send to the server (server has bufferedReader to read all data sent from client) then the server replies back to client (client uses bufferedReader to read all data sent from the server)