Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Java 

[Updated] Java Tutorial #2

Hi Psycho,

thats a nice tutorial. But I see one litte problem in the code for file input and file output.

Code
try
  {
  FileReader fr = new FileReader(fileName);
  BufferedReader br = new BufferedReader(fr);

  String line = br.readLine();

  while(line != null)
  {
    // display
  System.out.println(line);

    // get next line
    line = br.readLine();
  }

  br.close();
  }
  catch(Exception e)
  {
  System.out.println(e);
  }
You should close the reader within a finally-clause to get shure that it will also be closed after an exception.

Man, I had really trouble with this in a bigger project because someone didn't close streams like this. Some files couldn't be deleted sometimes and it took a while to figure out that open streams where blocking them.
This may not be a problem in a little program which stops running after the exception occured. But such things are forgotten soon, if one doesn't it right everytime.

This is a solution:
Code
FileReader fr;
        BufferedReader br = null;
        try {
            fr = new FileReader(fileName);
            br = new BufferedReader(fr);

            String line = br.readLine();

            while (line != null) {
                // display
                System.out.println(line);

                // get next line
                line = br.readLine();
            }

        } catch (Exception e) {
            System.out.println(e);
        } finally{
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
Deque
Thanks Deque. At the time of writing the original post (almost 2 years ago), it was even a learning experience for myself.
Great tutorial :)

I'm learning Java in college atm, but I'm trying to work ahead so I can get more experience. This is the first tutorial I've read that helped me understand input.

Thank you :D
thankyou soo soo much for this wonderful tutorial... The first tutorial i read and understood regarding file operations :)
Start feeding poor whenever you've got some extra bucks.Because there is no need for an occasion to feed them.
"Enna Paar, Naan Kaiya Thatta Undaachu Ulagam. Hey, Naan Sonna Pakkam Nikkaama Sozhalum. Dai, En Kooda Senthu Koothaadum Nezhalum. Ullaara Eppodhum Ulaala Ulaala"
wow psycho!U just rocked !help me on exceptional handling pls :)
Another great tut. I just relized php seems to be similar to java because this looks kinda the same. Noob thoughts


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C] by Recycle Bin.Nov 6, 2015 09:36 PM 61 6,283 Nov 6, 2015 09:36 PM
Last Post: TheUnCola
[Java] by President HolyFeb 8, 2014 11:48 AM 3 187 Feb 8, 2014 11:48 AM
Last Post: Knautschtabak
[Java] by Canonsx130Dec 18, 2013 10:57 AM 21 1,150 Dec 18, 2013 10:57 AM
Last Post: leto12