Thursday, October 18, 2007

How to write a File in Java

Code snippet on how to write a File in Java

Note: myFile.txt - file to be written

Java Imports:
java.io.BufferedWriter,
java.io.FileWriter,
java.io.IOException

Code Snippet:
try {
// myFile.txt - file to write
FileWriter fileWriter = new FileWriter( "myFile.txt" );
BufferedWriter bufferedWriter = new BufferedWriter( fileWriter );
// write to a file line 0, line 1, line n
for( int index = 0; index < 10; index++ ) {
bufferedWriter.write( "line " +index+ "\n" );
}
// close writer
bufferedWriter.close();
} catch ( IOException ioe ) {
// handle exception
}

No comments:

Google