It's not a secret anymore!
The moose likes Java in General and the fly likes Reading one line from a text Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Reading one line from a text" Watch "Reading one line from a text" New topic
Author

Reading one line from a text

preethi Ayyappan
Ranch Hand

Joined: Oct 04, 2007
Posts: 518
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: 35252
    
    7
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 appsImageJ pluginsJava web charts
preethi Ayyappan
Ranch Hand

Joined: Oct 04, 2007
Posts: 518
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
    
    9
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
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: 12929
    
    3

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
Thank you for your help.Now it works fine.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Reading one line from a text
 
Similar Threads
list box
Byte order and file transference.
WA #1.....word association
Default Body Content
exporting to CSV