No. It cannot be the final destination of data, so it should be connected to some other stream.
The updated example program uses a BufferedWriter
and a PrintWriter
.
Look at the file it creates with NotePad (or other text editor).
The lines of text should appear correctly separated
(with the earlier examples they might not).
import java.io.*; class WriteTextFile3 { public static void main ( String[] args ) { String fileName = "reaper.txt" ; PrintWriter print = null; try { print = new PrintWriter( new BufferedWriter( new FileWriter( fileName ) ) ); } catch ( IOException iox ) { System.out.println("Problem writing " + fileName ); } print.println( "No Nightingale did ever chaunt" ); print.println( "More welcome notes to weary bands" ); print.println( "Of travellers in some shady haunt," ); print.println( "Among Arabian sands." ); print.close(); } }
Opening the file might throw an exception, so a try/catch
structure
is needed for the constructor.
However the println()
statements can be moved outside of the
structure.