Tuesday, August 4, 2015

[Java] Writing Text to a File

Java class that writes text to a file.




import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteTextToAFile {
   private static FileWriter fileWriter;
   private static BufferedWriter bufferedWriter;

   public static void main(String[] args) {
     try {
      fileWriter = new FileWriter("temp.txt");
      bufferedWriter = new BufferedWriter(fileWriter);
      bufferedWriter.write("Hello world!");
      bufferedWriter.close();
      System.out.println("File write is successful.");
     } catch (IOException e) {
      e.printStackTrace();
     }finally{
       try {
         fileWriter.close();
         bufferedWriter.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }

    }//End main method

}//End class



No comments:

Post a Comment