Wednesday, December 8, 2010

java random access file rotating

This code provides a file which is random access,
rotating by means firstly fixed file size
and after the reaching the limit
it'll delete first lines and append new content at the end of file.

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Calendar;

public class RotateRAF
{
public static int Size = 2048;
public RotateRAF(String message, String fileName) throws IOException
{
Calendar cal = Calendar.getInstance();
String time = cal.getTime().toString();
RandomAccessFile raf = new RandomAccessFile(fileName,"rw");
if(raf.length() <= Size)
WriteToRAF(fileName, time, message);
else{
deleteRAF(fileName);
WriteToRAF(fileName, time, message);
}
}
public static void WriteToRAF(String fileName,String time,String message)
throws IOException
{
try
{
RandomAccessFile raf = new RandomAccessFile(fileName,"rw");
raf.seek(raf.getFilePointer());
raf.seek(raf.length());
raf.writeBytes(time);
raf.writeBytes(" ");
raf.seek(raf.length());
raf.writeBytes(message);
raf.seek(raf.length());
raf.writeBytes("\n");
} catch (FileNotFoundException e)
{e.printStackTrace();}
}

public static void deleteRAF(String fileName) throws IOException
{
try
{
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
long pos = 0;
while ( raf.readLine() != null) {
//Create a byte[] to contain the not deleted contents of the file.
// and truncate the file to the pos. of deleted the contains.
byte[] notDeleted = new byte[(int) (raf.length() - raf.getFilePointer())];
raf.read(notDeleted);
raf.getChannel().truncate(pos);
raf.seek(pos);
raf.write(notDeleted);
pos += raf.getFilePointer();
return;
} catch (FileNotFoundException e)
{e.printStackTrace();}
}

public static void main(String args[]) throws IOException
{
for(int i=0;i<=10;i++){
RotateRAF("Computers are useless. They can only give you answers.Pablo Picasso",
"rotateRAF.txt");
RotateRAF("The Internet? Is that thing still around?.Homer Simpson",
"rotateRAF.txt");
}
}

}

No comments:

Post a Comment