File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to print out first few lines of a file?

 
drew taylor
Greenhorn
Posts: 21
  • 0
  • 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
Pie
Posts: 12021
25
Chrome Java Linux
  • 0
  • 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
  • 0
  • 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
Pie
Posts: 20187
26
MySQL Database
  • 0
  • 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
Pie
Posts: 12021
25
Chrome Java Linux
  • 0
  • 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...
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic