aspose file tools*
The moose likes Beginning Java and the fly likes How to print out first few lines of a file? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to print out first few lines of a file?" Watch "How to print out first few lines of a file?" New topic
Author

How to print out first few lines of a file?

drew taylor
Greenhorn

Joined: Feb 20, 2006
Posts: 21
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

Joined: Oct 02, 2003
Posts: 11314
    
  16

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.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
drew taylor
Greenhorn

Joined: Feb 20, 2006
Posts: 21
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
Bartender

Joined: Oct 14, 2005
Posts: 18570
    
    8

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

Joined: Oct 02, 2003
Posts: 11314
    
  16

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...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to print out first few lines of a file?