File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Reading one line from a text Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
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: 39548
    
  27
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.


Ping & DNS - updated with new look and Ping home screen widget
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: 3169
    
  10
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
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13875
    
  10

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://aspose.com/file-tools
 
subject: Reading one line from a text
 
Similar Threads
Default Body Content
list box
exporting to CSV
WA #1.....word association
Byte order and file transference.