Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to close FileInputStream?

I am working as a trainee in Test Automation. I am working with creating Junit code with Eclipse and run using Eclipse. In that I am retriving the datas from excel sheet using FileInputStream function.

FileInputStream fi=new FileInputStream("c:\\search.xls"); Workbook w=Workbook.getWorkbook(fi); Sheet s=w.getSheet(0); 

Is it necessary to close the Inputstream function? If it so please guide me with some codings.

like image 862
Olaganathan.S Avatar asked Feb 23 '11 12:02

Olaganathan.S


People also ask

Does FileInputStream need to be closed?

close() method. After any operation to the file, we have to close that file.

What happens if you don't close InputStream?

resource-leak is probably more of a concern here. Handling inputstream requires OS to use its resources and if you don't free it up once you use it, you will eventually run out of resources.

Should I close FileOutputStream?

No, you only need to close the outermost stream. It will delegate all the way to the wrapped streams. However, your code contains one conceptual failure, the close should happen in finally , otherwise it's never closed when the code throws an exception between opening and closing.

Do I need to close InputStreamReader?

It's important to close any resource that you use. in. close will close BufferedReader, which in turn closes the resources that it itself uses ie. the InputStreamReader.


2 Answers

Yes, you need to close the inputstream if you want your system resources released back.

FileInputStream.close() is what you need.

like image 108
asgs Avatar answered Oct 03 '22 06:10

asgs


FileInputStream fi=null; try {     fi=new FileInputStream("c:\\search.xls");     Workbook w=Workbook.getWorkbook(fi);     Sheet s=w.getSheet(0); } finally {     if (fi!=null) {         fi.close();     } } 
like image 20
Axel Avatar answered Oct 03 '22 07:10

Axel