Sample Programs

Sample java program to write to file using FileWriter

 package org.jusfortechies.example; 

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

 public class WriteFile {

   public static void main(String[] args) {

     String strFilePath = "C:\\textfile.txt";
     try {
       // Create file
       FileWriter fstream = new FileWriter(strFilePath);

       BufferedWriter out = new BufferedWriter(fstream);
       out.write("This is sample text to test FileWriter in java.");

       // Close the output stream
       out.close();

     } catch (FileNotFoundException ex) {
       System.err.println("Error: " + ex.getMessage());

     } catch (IOException ioe) {
       System.err.println("Error: " + ioe.getMessage());
     }
   }

 }



blog comments powered by Disqus