Wednesday, May 9, 2012

How to add content, append content in File in Java with example using RandomAccessFile

How to Add content ot append content in existing file using RandomAccessFile in Java with Example
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Date;
 
public class ContentAppendToFileExample 
{
    public static void main( String[] args )
    { 
     try 
     {
     String contentToAddedAtTheEndOfFile = "\nThis content will added/append to the end of the file at "+new Date();
     File file =new File("D:\\db\\fileTest\\file1.txt");
         RandomAccessFile raf = new RandomAccessFile(file, "rw");

         // Seek to end of file
         raf.seek(file.length());

         // Append to the end
         raf.writeBytes(contentToAddedAtTheEndOfFile);
         raf.close();
     } 
     catch (IOException e) 
     {
      e.printStackTrace();
     }
    }
}

No comments:

Post a Comment