Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Issue with close() method of BufferedReader class and FileInputStream class

763890Feb 14 2010 — edited Feb 15 2010
I have written the following code to a text file, called hello,txt from Windows. Everything works fine but I am trying to figure out whether calling of close() method of aforemetioned class is appropriate or necessary thing to do.

Here are the questions:
1. Is it necessary to call close method in this senario? And why? [it seems to me that everything gets cleaned up automatically anyways at the end of each call to the method when called from main()]

2. If the answer for No.1 is yes, then in which order each close method should be called? Or, does the order of calling close method matter anyways?

3. Is the reason for why in No.1 is that because calling close method on each object is a necessary step to do when dealing with mutli-thread?

Thanks for your help in advance!
	/**
	 * Below is an example to clarify my questions
	 */
	void readWinFile() {
		File objFile = new File("hello.txt");
		FileInputStream fileStream = null;
		BufferedReader bfReader = null;

		try {
			fileStream = new FileInputStream(objFile);
			bfReader = new BufferedReader(
                                  new InputStreamReader(fileStream, "MS932"));

			int tmp;
			while ((tmp = bfReader.read()) != -1) {
				System.out.print((char)tmpLine);
			}
		} catch (FileNotFoundException e) {
			System.err.printf("File: %s Not Found @ DIR = %s", 
                                   objFile.getName(), objFile.getParent());
		} catch (UnsupportedEncodingException e) {
			System.err.printf("Internal failure: %s", e);
		} catch (IOException e) {
			System.err.printf("File: %s close failure", objFile.getName());
*		} finally {*
*			if (bfReader != null) {*
*				try {*
*					bfReader.close();*
*				} catch (IOException e) {*
*					e.printStackTrace();*
*				}*
*			}*
*			if (fileStream != null) {*
*				try {*
*					fileStream.close();*
*				} catch (IOException e) {*
*					e.printStackTrace();*
*				}*
*			}*
*		}*	
}
Edited by: Jay-K on Feb 14, 2010 8:50 PM

Edited by: Jay-K on Feb 14, 2010 8:52 PM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 15 2010
Added on Feb 14 2010
9 comments
1,177 views