Forums Register Login

how to read lines from a file

+Pie Number of slices to send: Send
i have a txt file.
ex:
dmk.del.423543.dffd555.23434
dmk.del.423543.dffd555.23435
dmk.del.423543.dffd555.23436
dmk.del.423543.dffd555.23437
sample.txt
i have to read the content of the sample txt file by line by line...
Please let me know what modifications i have to do in the following code..
class SampelRead
{
public static void main(String[] args)
{
try{
BufferedReader br_reader = new BufferedReader(new FileReader("sample.txt"));
String strin = br_reader.readLine();
System.out.println("Line ::"+strin);

}catch(IOException objIOException)
{}
}
}
Thanks
Sravam
[ August 07, 2003: Message edited by: sravan reddy ]
+Pie Number of slices to send: Send
As is, it should basically work and display the first line of the file (you'd want to add "import java.io.*;" at the top.) I do have plenty of critiques, though, and then finally I'll tell you how to read all the lines.
First, you've forgotten to close the file. After you're through working with a file, you have to close it so the OS can reclaim the resources associated with keeping it open. You can simply add "br_reader.close();" as the last line at the end of the try block.
Second, NEVER write an empty catch block like the one you have here. If an exception is thrown, and your catch block does nothing, then your program will simply not work, and you won't know why. You'll spend hours trying to figure out what happened. If instead your catch block contained a trivial "objIOException.printStackTrace();" then you would have gotten a nice explanation of the problem, fixed it, and moved on.
Third (and now I'm starting to get picky) your variables names are inconsistent and not especially well chosen. All three of the names include some form of the data type, which is rarely done in Java, as Java (unlike C) is strongly typed. But each of the names uses a different convention to encode the type! br_reader uses initials and an underscore, "strin" uses an oddly truncated version of the class name, and objIOException uses capitalization and puts the type at the end. Spending a moment to thing of appropriate variable names will make your programs easier to understand. I'd probably use "reader", "line", and "error" for these three, respectively.
Finally, how do you read all of the lines? Using a "while" loop would be one way. The body of your try{} block could look like this (BufferedReader returns "null" on end-of-file):
No holds barred. And no bars holed. Except this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 996 times.
Similar Threads
incomparable types: boolean and null
Problem reading a file through BufferedReader
Anyone help me out with this error
BufferedWriter, PrinterWriter etc
reaind text file and finding column avg
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 09:19:24.