Friday, November 2, 2012

Writing strings to a file in Java

Here is an example of a Java program which writes strings to a file


package com.giri.test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class FileWriting {
 
 private static final String fileName = "test.txt";
    private static FileOutputStream fos = null;
    private static File file;
    
   public static void writeStringToFileOutputStream ( FileOutputStream fos , String myString ) throws Exception {
    try {
        myString = myString + "\r\n";
        byte[] byteArray = myString.getBytes( "UTF-8" );
        fos.write( byteArray );
    } catch(Exception e) {
     e.printStackTrace();
     throw new Exception("Error while writing string to file output stream !");
    }
   }

 
 public static void main(String[] args) {
  
  file = new File( fileName );
  
  try {
   fos = new FileOutputStream(file);
  } catch (FileNotFoundException e) {
   System.out.print("Could not create new file object for the file " + fileName);
   e.printStackTrace();
   return;
  }
  
  try {
   writeStringToFileOutputStream(fos, "File write test !");
   writeStringToFileOutputStream(fos, "This is Giridhar Bhujanga");
   writeStringToFileOutputStream(fos, "Over and out..!");
  } catch(Exception e) {
   System.out.println("Error in writing the specified string !");
   e.printStackTrace();
  } finally {
   try {
    fos.close();
   } catch(Exception e) {
    System.out.println("Error in closing the file output stream object !");
   }
  }
 }
}

Output:


File write test !
This is Giridhar Bhujanga
Over and out..!

No comments :

Post a Comment