I have this little program (shown below). The program gives me the expected output and I can print the output to the console System.out.println(result); I also want to write the output to a file. However, the program does not write anything to the file I specified. I got a blank file. What mistake did I make?
[ December 31, 2002: Message edited by: JiaPei Jen ] [ December 31, 2002: Message edited by: JiaPei Jen ] [ December 31, 2002: Message edited by: JiaPei Jen ]
Hi Jen, Assuming that you are executing your java class on a Windows machine, the only mistake I saw in your code was the name of the file you are trying to write to. The correct line of code should be:
Closing the output file when you're done with it would be a good idea - that will also flush it. But I don't think that's the biggest problem here. You're creating a new FileOutputStream each time you find a match to the pattern "Administrative Contact". Because you use the constructor new FileOutputStream(File), the new stream will overwrite any previous file, effectively replacing it with a new file that contains only the most recent information. To avoid this, you have two options: (1) Use the constructor new FileOutputStream(File, boolean) instead, setting the second argument to true in order to append rather than overwrite. E.g. "new FileOutputStream(fout, true)". (2) Create the FileOutputStream outside the loop, so it just happens once, and each time out.write() is called inside the loop it's appended to the same file. Then close the stream once after the loop is completed. The second method is probably what you want here. Note that it's also possible to do a number of other things before the loop, such as compiling the Pattern (since it's always the same, each time through the loop). Also, are you sure that the pattern is even being found in the data you're looking at? Is the line
causing something to be printed? You may want to modify it a bit to give it a more distinctive label to be sure:
flush the stream after every write operation.. out.write(what-ever); out.flush(); the when you are closing the inputstream object close the out too. If you do not close or flush, the data will be only in the stream, but not written to disk. Regds Lupo
"In the country of the blind, the one eyed man is the King"
Gautham Kasinath CV at : http://www.geocities.com/gkasinath
Evildoers! Eat my justice! And this tiny ad's justice too!
a bit of art, as a gift, that will fit in a stocking