BufferedReader not closed warning not disappearing - java

I am using a BufferedReader, and though I call the close() method, eclipse still gives me a warning.
Eclipse does not give me a warning if I place the close() call before the while, but in then the code does not work.
Is there either an error in my code, or what else is the problem?
Code:
Hashtable<String, Hashtable<String, Integer>> buildingStats = new Hashtable<String, Hashtable<String, Integer>>();
try
{
BufferedReader br = new BufferedReader(new FileReader(new File("Assets/Setup/Buildings.txt"))); // Sets the buildings values to the values in Buildings.tx
String line;
int lineNum = 0;
while((line = br.readLine()) != null)
{
++lineNum;
String[] values = line.split(",");
if (values.length != 3)
throw new Exception("Invalid data in Assets/Setup/Buildings.txt at line " + lineNum);
if (buildingStats.containsKey(values[0]))
{
buildingStats.get(values[0]).put(values[1], Integer.parseInt(values[2]));
}
else
{
buildingStats.put(values[0], new Hashtable<String, Integer>());
buildingStats.get(values[0]).put(values[1], Integer.parseInt(values[2]));
}
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return buildingStats;

You should put it in a finally method like so:
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File("Assets/Setup/Buildings.txt")));
// do things
} catch (Exception e){
//Handle exception
} finally {
try {
br.close();
} catch (Exception e){}
}
If you still get the warning try cleaning and rebuilding your eclipse project.

Pretty much anything between the declaration and close() call can throw an exception, in which case your close() will not be called. Try putting it in a finally block.

Related

Why I can't test for FileNotFoundException in java JUnit 4.13

I am facing some difficulties with testing constructor of my class using JUnit 4.13. What I am trying to do is to test that constructor is throwing FileNotFoundExeption when I pass wrong file name.
This is my constructor (parameter 'file' is name of file where I store languages):
public LanguageManager(String file) {
this.languages = new ArrayList<Language>();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
String line;
while((line = in.readLine()) != null) {
line = line.trim();
if (line.equals("") || line.startsWith("#"))
continue;
Language j = new Language(line);
this.languages.add(j);
}
in.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This is my function for testing this constructor:
#Test(expected=FileNotFoundException.class)
public void testLanguageManager() {
LanguageManager ajm = new LanguageManager("non_existing_file.txt");
}
I suspect that there is problem with try catch block in constructor but can't figure out what I am doing wrong. Any help is appreciated.

Why is eclipse complaining when I try to close BufferedReader in finally block?

Here is my code:
public static String readFile()
{
BufferedReader br = null;
String line;
String dump="";
try
{
br = new BufferedReader(new FileReader("dbDumpTest.txt"));
}
catch (FileNotFoundException fnfex)
{
System.out.println(fnfex.getMessage());
System.exit(0);
}
try
{
while( (line = br.readLine()) != null)
{
dump += line + "\r\n";
}
}
catch (IOException e)
{
System.out.println(e.getMessage() + " Error reading file");
}
finally
{
br.close();
}
return dump;
So eclipse is complaining about an unhandled IO exception caused by br.close();
Why would this cause an IO exception?
My second question is why eclipse doesn't complain about the following code:
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try{
// open input stream test.txt for reading purpose.
is = new FileInputStream("c:/test.txt");
// create new input stream reader
isr = new InputStreamReader(is);
// create new buffered reader
br = new BufferedReader(isr);
// releases any system resources associated with reader
br.close();
// creates error
br.read();
}catch(IOException e){
// IO error
System.out.println("The buffered reader is closed");
}finally{
// releases any system resources associated
if(is!=null)
is.close();
if(isr!=null)
isr.close();
if(br!=null)
br.close();
}
}
}
I'd appreciate it if you kept the explanation in Laymen's terms if possible. Thanks for the help in advance
Both code examples should have compiler errors complaining about an unhandled IOException. Eclipse shows these as errors in both code examples for me.
The reason is that the close method throws an IOException, a checked exception, when called in the finally block, which is outside a try block.
The fix is to use a try-with-resources statement, which is available in Java 1.7+. The resources declared are implicitly closed.
try (BufferedReader br = new BufferedReader(new FileReader("dbDumpTest.txt")))
{
// Your br processing code here
}
catch (IOException e)
{
// Your handling code here
}
// no finally necessary.
Prior to Java 1.7, you need to wrap the calls to close() in their own try-catch blocks inside the finally block. It's a lot of verbose code to ensure that everything is closed and cleaned up.
finally
{
try{ if (is != null) is.close(); } catch (IOException ignored) {}
try{ if (isr != null) isr.close(); } catch (IOException ignored) {}
try{ if (br != null) br.close(); } catch (IOException ignored) {}
}

How to handle IOException when closing bufferedReader

Hi I am learning about Exceptions in Java and I encountered a problem with this situation.
public static void main(String[] args){
String path = "t.txt";
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(path));
StringBuilder sbd = new StringBuilder();
String line = br.readLine();
while(line != null){
sbd.append(line);
sbd.append(System.lineSeparator());
line = br.readLine();
}
String result = sbd.toString();
System.out.print(result);
}catch(IOException e){
System.out.println(e.getMessage());
}finally{
if (br != null)
br.close(); //Here it says unreported exception IOException; must be caught or declared to be thrown
}
}
when I call method close() to close the bufferedReader, it says unreported exception IOException; must be caught or declared to be thrown.
I know that JAVA 7 provides a pretty easy way to do the clean-up with
try(br = new BufferedReader(new FileReader(path))){
//....
}
but prior to JAVA 7, what can I do with this situation? adding "throws IOException" right next to the main function declaration is a way to fix that but is it a little bit complicated since I have had a catch section to catch IOExceptions
You wrapped it into another try-catch
}finally{
if (br != null)
try {
br.close(); //Here it says unreported exception IOException; must be caught or declared to be thrown
} catch (Exception exp) {
}
}
Now, if you care or not is another question. To my mind, your intention here is to make all best effort to close the resource. If you want, you could use flag and set it to true in the parent catch block (indicating that any following errors should be ignored) and if it's false in the close catch block, display an error message, for example...
boolean hasErrored = false;
try {
//...
}catch(IOException e){
e.printStackTrace();
hasErrored = true;
}finally{
if (br != null)
try {
br.close(); //Here it says unreported exception IOException; must be caught or declared to be thrown
} catch (Exception exp) {
if (!hasErrored) {
// Display error message...
}
}
}
prior to JAVA 7, what can I do with this situation?
You can add a try-catch in the finally block like,
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
// Handle the IOException on close by doing nothing.
}
}
}
add another try catch block
...
if(br != null)
try{
br.close();
} catch (IOException io){
}
I generally code it thus:
} finally {
if (br != null) {
try {
br.close();
} catch(IOException ioe) {
// do nothing
}
}
}
In fact, I once wrote a util class containing methods such as closeStream(final InputStream stream), closeStream(final OutputStream stream), closeReader(final Reader reader), etc that hides all this stuff, since you end up using it all the time.
This is approximately how try-with-resources closes resources
BufferedReader br = new BufferedReader(new FileReader(path));
IOException ex = null;
try {
br.read();
// ...
} catch(IOException e) {
ex = e;
} finally {
try {
br.close(); // close quietly
} catch (IOException e) {
if (ex != null) {
ex.addSuppressed(e);
} else {
ex = e;
}
}
}
if (ex != null) {
throw ex;
}

Resource leak in my java program

I am trying to write a method in java, where I take some information from a file and see if the file has the information the user looks for. However, for the code that I present, eclipse signs that I have an resource leak in line "return true;" and that the "br = new BufferedReader(fr);" is never close, despite the fact that I am using the close() method at the end of the program. Apparently I am missing something. Could someone help me figure out what is happening? Great thanks in advance!
import java.io.*;
class Help{
String helpfile;
Help(String fname){
helpfile = fname;
}
boolean helpon(String what){
FileReader fr;
BufferedReader br;
int ch;
String topic, info;
try{
fr = new FileReader(helpfile);
br = new BufferedReader(fr);
}
catch(FileNotFoundException e){
System.out.println(e);
return false;
}
try{
do{
ch = br.read();
if(ch=='#'){
topic = br.readLine();
if(what.compareTo(topic) == 0){
do{
info = br.readLine();
if(info!=null)
System.out.println(info);
}while((info!= null) && (info.compareTo("")!= 0));
return true;
}
}
}while(ch!=-1);
}
catch(IOException e){
System.out.println(e);
return false;
}
try{
br.close();
}
catch(IOException e){
System.out.println(e);
}
return false;
}
}
The issue is that you're returning before the program gets the chance to close the resource. There are 2 ways to fix this issue:
Put the returns after you close the resource (by possibly putting the return result in a boolean).
Modify your code to put the close in a finally block so any return done will still execute that code.
Number 2 is generally a more accepted practice because then if you add more things in the future you are still guaranteed to close the resource (unless a catastrophic event occurs).
boolean helpon(String what){
FileReader fr;
BufferedReader br;
int ch;
String topic, info;
try{
fr = new FileReader(helpfile);
br = new BufferedReader(fr);
do{
ch = br.read();
if(ch=='#'){
topic = br.readLine();
if(what.compareTo(topic) == 0){
do{
info = br.readLine();
if(info!=null)
System.out.println(info);
}while((info!= null) && (info.compareTo("")!= 0));
return true;
}
}
}while(ch!=-1);
} catch(IOException e){
System.out.println(e);
return false;
} catch(FileNotFoundException e){
System.out.println(e);
return false;
} finally {
try {
if (br != null) {
br.close();
}
} catch(IOException e){
System.out.println(e);
return false;
}
}
}
You have return statements all over the method, but only have a br.close() at the end. It's possible in the flow of code that the method will be returned leaving the br still open.
You may be interested in using try with resources
try (
FileReader fr = new FileReader(helpfile);
BufferedReader br = new BufferedReader(fr)
)
{
//your code
}
catch (IOException e)
{
//error
}
With this, the close methods will automatically be called for you on the resources.
You should put the call to close() in a finally block. In the current state, your code will never reach the final try/catch because you are returning true or false.
try {
fr = new FileReader(helpfile);
br = new BufferedReader(fr);
do {
ch = br.read();
if(ch=='#'){
topic = br.readLine();
if(what.compareTo(topic) == 0){
do{
info = br.readLine();
if(info!=null)
System.out.println(info);
}while((info!= null) && (info.compareTo("")!= 0));
return true;
}
}
}while(ch!=-1);
} catch (IOException e) {
System.out.println(e);
return false;
} catch (FileNotFoundException e) {
System.out.println(e);
return false;
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
System.out.println(e);
}
}
If you're using Java 7, use the try-with-resources functionality:
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

How to read line from txt?

How can I read line from text? Look at my code:
public static String getTemplateFromFile() {
String name = null;
try {
BufferedReader reader = new BufferedReader(new
FileReader(
"http://localhost:8080/blog/resources/cache/templateName.txt"));
name = reader.readLine();
//name="TEST";
//NULL anyway
reader.close();
}
catch (Exception e) {
}
return name;
}
Also I have got secnod version, but my server freeze.
public static String getTemplateFromFile() {
String name = null;
/*
try {
URL url = new URL("http://localhost:8080/blog/resources/cache/templateName.txt");
Scanner s = new Scanner(url.openStream());
name=s.nextLine();
s.close();
}
catch(IOException ex) {
ex.printStackTrace();
}*/
return name;
}
I think it can't close connection or something.
It returns me NULL even I say name="TEST"; in try construction.
FileReader is exactly that – a class that reads from files, not HTTP requests.
You're getting an invalid file path exception, which you're then ignoring in your evil empty catch block.
Instead, you should use URLConnection.
Try this
try{
URL reader=new URL("http://localhost:8080/blog/resources/cache/templateName.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(reader.openStream()));
name = br.readLine();
//name="TEST";
br.close();
}catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
AFAIK, URL#openStream() internally calls URL#openConnection() which creates an instance of URLConnection and calls URLConnection#getInputStream() on it.

Categories