Discussion Locked

Read html file,Insert data,Output a file

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Hi,
I tried to read the document java.io.*. There are so many different classes and methods to use. For the beginner, I am confused. Could you please recommend the best way to code. If you have sample of code, that would be great.
I have an HTML file that needs to be read and remember to the point of the "" tag, then insert new data and finish reading the rest of the file and output to a new file.

Thank you very much,
Nhan Nguyen

3 replies

by jay eckles

I'm a big fan of BufferedReader and PrintWriter; the Java API Spec shows you an example of how to open a file with a BufferedReader:

BufferedReader in
= new BufferedReader(new FileReader("foo.in"));

where "foo.in" is the name of the file you want to read. Then, you can use the object "in" very similar to how you'd use System.in:

String line = in.readLine() ;

Then of course you could check to see if the line contains "", or you could count the number of lines you've reador whatever.

When you're ready to start writing the results to an output file, I use a PrintWriter:

PrintWriter out
= new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));

where again "foo.out" is the name of the file you wantto write to. Once you've set up the PrintWriter, you can use out similar to System.out:

out.println( line ) ; //line is a String

Don't forget to clean up after yourself and close your writers:
in.close() ;
out.close() ;

For more detailedinformation on BufferedReader and PrintWriter, see the Java API Specs at...

http://java.sun.com/j2se/1.3/docs/api/index.html
(remember to remove spaces from URL)

See specifically java.io.BufferedReader, java.io.BufferedWriter, and java.io.PrintWriter. java.io.FileWriter and java.io.File might also come in handy at some point.

Good luck.

Jay Eckles

This discussion is closed to new replies.