Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reading one line from a text

 
preethi Ayyappan
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
preethi Ayyappan
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
preethi Ayyappan
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply.if you show me in codes ,that will do better.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Preethi, it is very simple. Throw away your while-loop. Just call br.readLine() three times.
 
preethi Ayyappan
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your help.Now it works fine.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic