Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to print out first few lines of a file?

 
drew taylor
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please can someone help me with the following? I have tried looking on the net for an example progeam or a tutorial but I didn't find anything.

How can I make it so that my program prints out a specifed number of lines from a file (i.e a text file, html document)

Any hints, example code will be appresiated!
 
fred rosenberger
lowercase baba
Bartender
Posts: 12146
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
start by writing a program that opens a file. Get that to work.

Then, add code to close the file (just to be nice).

Then see if you can read a line. once that works, try to print the line.

etc.

start small, make sure it works at each step before tackling the next.
 
drew taylor
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I got it to work. I'm trying to modify an existing example class that gets the html information about a specified website. I did the following:

Instead of having:

while (in.hasNextLine()) {
System.out.println(" " + in.nextLine());
}

I modified it to:

Scanner in = new Scanner(u.getInputStream());

int i = 6;

while (i > 0) {
System.out.println(" " + in.nextLine());
i = i -1;
}
 
Paul Clapham
Sheriff
Posts: 21137
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That will work for many files. But there are some files where a problem will arise. Can you see what might cause that problem?
 
fred rosenberger
lowercase baba
Bartender
Posts: 12146
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As a general tip, if you know in advance how many times you want to do something, a for() loop is the preferred solution. there's no reason for it to my knowledge - it's just the idiom that's used.

but even if you did

you still might have a problem with small files...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic