Hack Forums
[Java] [Updated] Java Tutorial #2 - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Java] [Updated] Java Tutorial #2 (/showthread.php?tid=67945)

Pages: Pages 1 2


* - Knautschtabak - Jan 5, 2011

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


* - Psycho - Jan 5, 2011

Thanks Deque. At the time of writing the original post (almost 2 years ago), it was even a learning experience for myself.


* - seasnake_730 - Jan 14, 2011

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


* - ajayu1992 - Dec 7, 2011

thankyou soo soo much for this wonderful tutorial... The first tutorial i read and understood regarding file operations :)


* - Funn1k - Sep 6, 2012

wow psycho!U just rocked !help me on exceptional handling pls :)


* - mr.jitterbud - Mar 29, 2014

Another great tut. I just relized php seems to be similar to java because this looks kinda the same. Noob thoughts