Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Reading Java File  RSS feed

 
Alex Teslin
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

If i want to read a Java Application program and save it into my program, is the code below is the right one? I mean, reading lines is the correct approach or is there another way?

try {
FileInputStream f = new FileInputStream("My_File.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(f));

String line;
while ((line = input.readLine()) != null) {
fileCollection.add(line);
}
input.close();
}
catch (IOException e) {
}

Thank you guys
 
Paul Clapham
Sheriff
Posts: 22185
38
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to read a file that is made up of lines of text, then that is a good way to do it. But it could be improved a little bit. For example, if there is an IOException then you don't do anything and you don't tell anybody it happened. That makes it hard to identify problems when they occur. Also, if an exception occurs then it's possible you don't close the file properly. That can leave the file locked and prevent other tasks from accessing it. Handling the exceptions properly looks more like this:The "finally" block in that code will be called even if an exception occurred inside the "try" block. Even if it was a run-time exception like NullPointerException which you didn't catch.
 
Alex Teslin
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Paul,

You was right, i missed lots of things there and thanks for a nice code example. I have however, one question about finally clause. If I use finally, do i still need a catch clause before finally?

Thank you again
 
Paul Clapham
Sheriff
Posts: 22185
38
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you don't. Try-finally works just the same way as try-catch-finally. So if that code was contained in a method that was declared as "throws IOException", you could leave out the catch-clause.
 
Alex Teslin
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, my method is declared with throws.
Thanks again with your swift replies.
 
Species Terminator
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
okie i hope u got a nice answer..if u need any answer please visit http://www.coollinks2others.blogspot.com/
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!