Forums Register Login

Reading Java File

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Yes, my method is declared with throws.
Thanks again with your swift replies.
+Pie Number of slices to send: Send
okie i hope u got a nice answer..if u need any answer please visit http://www.coollinks2others.blogspot.com/
30 seconds to difuse a loaf of bread ... here, use this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1127 times.
Similar Threads
Problem with renaming file after reading it
Problem reading a file
Skip Reading several Lines using BufferedReader
InputStream,how to use
Problem with Reading very long line using bufferedReader
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 02:35:21.