Appending data to existing file

This example explains how data can be appended to files by using the RandomAccessFile class. The RandomAccessFile class allows to read and write data at any arbitrary location in an existing file. The following example illustrates how it can be used to append text/binary data at the end of files.

The overloaded methods “append” accept a string or byte array to write at the end of a given file. The method opens the file, appends data to the file and closes it.

A typical use of this function could be in applications that keep logging data periodically. In this case, logs can be appended to the end of a file using this example.

Code

/*
 * This example lists out the properties of a File and demonstrates 
 * how a File Object can be used. 
 *
 * Comments about individual functions are interspersed. 
 * @author Anand Hariharan ([email protected]) 
 *
 */
import java.io.*;

/*
 * A convienience class to append data to files. 
 * The class makes use of the RandomAccessFile to seek 
 * the end of the file and append the data. 
 */
public class Appender
{

    public static void append(String fileName, String text) throws Exception
    {
        File f = new File(fileName);

        if(f.exists())
        {
            long fileLength = f.length();
            RandomAccessFile raf = new RandomAccessFile(f, "rw");
            raf.seek(fileLength);

            raf.writeBytes(text);

            raf.close();
        }
        else
        {
            throw new FileNotFoundException();
        }

    }


    public static void append(String fileName, byte[] bytes) throws Exception
    {
        File f = new File(fileName);

        if(f.exists())
        {
            long fileLength = f.length();
            RandomAccessFile raf = new RandomAccessFile(f, "rw");
            raf.seek(fileLength);

            raf.write(bytes);

            raf.close();
        }
        else
        {
            throw new FileNotFoundException();
        }
    }


    public static void main(String[] args)
    {
        try
        {
            append("c:\\tmp.txt", "Appended Data");
        }
        catch(FileNotFoundException fnfe)
        {
            System.out.println("c:\\tmp.txt does not exist");
        }
        catch(Exception e)
        {
        }

        try
        {
            append("c:\\tmp.bin", new String("Appended Data").getBytes());
        }
        catch(FileNotFoundException fnfe)
        {
            System.out.println("c:\\tmp.bin does not exist");
        }
        catch(Exception e)
        {
        }


    }
} 
0

Leave a Reply