Closing IO Streams

Z

ZOCOR

Hi

Consider:

try
{
FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr);
doSomething();
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}

Questions:

1. Do i also need to close FileReader fr by doing fr.close?
2. if I want to parse a new file, do i just make fr point to a new object
say fr = new FileReader("file2.txt")? or start over again?

Thanks in advance

ZOCOR
 
C

Carlo Pellegrini

ZOCOR said:
Hi

Consider:

try
{
FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr);
doSomething();
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}

Questions:

1. Do i also need to close FileReader fr by doing fr.close?

No, the underlying stream is closea as well.
2. if I want to parse a new file, do i just make fr point to a new object
say fr = new FileReader("file2.txt")? or start over again?

No, you must start over again. The variable br holds a reference of the old
FileReader.

CarloP.
 
Z

ZOCOR

No, the underlying stream is closea as well.


No, you must start over again. The variable br holds a reference of the old
FileReader.

But the old FileReader now points to something else:

fr = new FileReader("file2.txt");

br holds a reference to fr and fr is now something different, so it should
work right?


ZOCOR
 
M

Michael Borgwardt

However, the close() call should happen in a finally
block after the catch, otherwise, the stream will
remain open if an exception is thrown.
But the old FileReader now points to something else:

fr = new FileReader("file2.txt");

No, it is the variable that has the name "fr" in your code
that holds a reference which points at a new object.

br holds a reference to fr

No, the object at which the reference in br points holds a copy of the value
of fr at the time the br object was created, i.e. a reference to the object
fr pointed at at that time. That reference does not change, no matter what
you do.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top