Author
Reading one line from a text
preethi Ayyappan
Ranch Hand
Joined: Oct 04, 2007
Posts: 518
posted Dec 05, 2007 03:00:00
0
Hi I am having ten lines in my text file.I want to read first and third line.please help me with a sample code. Thanks
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35442
posted Dec 05, 2007 03:58:00
0
I'd suggest to read the first 3 lines, and simply to ignore the second line. Here's some example code that reads from a file line by line.
Android apps – ImageJ plugins – Java web charts
preethi Ayyappan
Ranch Hand
Joined: Oct 04, 2007
Posts: 518
posted Dec 05, 2007 04:21:00
0
I am already having a code which reads line by line.but i need to read only the first 3 lines out of 10 lines. Code: import java.io.*; class FileRead1 { public static void main(String args[]) { try{ FileInputStream fstream = new FileInputStream ("myfile.txt"); DataInputStream in = new DataInputStream (fstream); BufferedReader br = new BufferedReader (new InputStreamReader (in)); String strLine; while ((strLine = br.readLine()) != null) { System.out.println (strLine); } in.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } }
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
Instead of having a loop, just read the first line and do what you need to do with it, read the second line and ignore it, read the third line and do what you need to do with it and then close the input stream.
Joanne
preethi Ayyappan
Ranch Hand
Joined: Oct 04, 2007
Posts: 518
posted Dec 05, 2007 04:39:00
0
Thanks for your reply.if you show me in codes ,that will do better.
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12953
Preethi, it is very simple. Throw away your while-loop. Just call br.readLine() three times.
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
preethi Ayyappan
Ranch Hand
Joined: Oct 04, 2007
Posts: 518
posted Dec 05, 2007 20:55:00
0
Thank you for your help.Now it works fine.
subject: Reading one line from a text