You need to 1) open the file, 2) parse XML; 3) close the file. In your SAX handler, replace you
System.out.println(...)
with the statement writing to the file.
Let's consider writing to the file separately, parsing separately, and the put it all together.
First, let's assume you want to write some parsed data to a text file. For writing, let's use the class
java.io.PrintWriter
:
https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html[
^].
So, writing to the file looks like
PrintWriter writer = new PrintWriter(outputFileName, encoding);
writer.println("some text");
writer.close();
This scenario looks very similar if you write in binary form; then you can use the class
java.io.FileOutputStream
:
https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html[
^].
To put it all together, you have to pass the reference to the writer to each of your handler methods where you write something. How? you don't have parameters for this purpose. Through implicit "this" parameter, which is a reference to the instance. Therefore, you need to have a reference to the writer as a member of the SAX handling class, an instance field.
The simplest scenario looks like this: add a class constructor to accept either the writer (or binary stream) reference, or the file name (then you create a writer instance or binary stream from the name in that constructor). Assign the obtained writer/stream reference to your field. In each of the SAX handler methods, use this reference for writing. At the end of parsing, close the file. If your constructor created the writer/stream object, close it in the destructor. If you passed already created writer/stream from external code, close the file in external code after parsing.
—SA