Demonstration of writing from an array to a file using a FileWriter object.
@author
@version
import java.util.Scanner;
import java.io.FileWriter;
import java.io.Writer;
import java.io.IOException;
public class FileWriterExample {
Close a Writer object (if it's valid)
@param file
public static void closeWriter( Writer file ){
try{
if( file != null ){
System.out.println("Reference is valid, so (attempting to) close the file...");
file.close();
}
}catch( IOException e ){
System.out.println("ERROR: IOException when attempting to close the file: " + e.getMessage() );
}
}
public static void main(String[] args) {
Scanner stdinScanner = new Scanner( System.in );
String userInput;
String filename;
FileWriter out = null;
System.out.print("Please enter a joke: ");
userInput = stdinScanner.nextLine();
System.out.print("Please enter where a filename (of where to save your joke): ");
filename = stdinScanner.next();
try{
out = new FileWriter( filename );
for( int i = 0; i < userInput.length(); ++i ){
char ch = userInput.charAt(i);
System.out.println("Writing " + ch + ".");
out.write( ch );
}
out.write( '\n' );
}catch( IOException e ){
System.out.println( "IOException: " + e.getMessage() );
}finally{
closeWriter( out );
}
}
}