Wednesday, May 9, 2012

How to write content into file in Java using FileOutputStream with example

Here is the example to write content into file using FileOutputStream in Java

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
 
public class WriteFileExampleUsingFileOutputStream
{
 public static void main(String[] args)
 {
  FileOutputStream fos = null;
  File file;
  String fileContent = "Content Added  on "+new Date();
  try 
  {
   file = new File("d:\\db\\fileTest\\newfile.txt");
   fos = new FileOutputStream(file);
 
   //first check if the file is already there, if no file found then create new file
   if (!file.exists()) 
   {
    file.createNewFile();
    System.out.println("File Created Succefssfully");
   }
    // get the content in bytes
   byte[] contentInBytes = fileContent.getBytes();
 
   fos.write(contentInBytes);
   fos.flush();
   fos.close();
 
   System.out.println("Content written Succefssfully");
  } 
  catch (IOException e) 
  {
   e.printStackTrace();
  } 
  finally 
  {
   try
   {
    if (fos != null)
    {
     fos.close();
    }
   } 
   catch (IOException e) 
   {
    e.printStackTrace();
   }
  }
 }
}

No comments:

Post a Comment