Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

RandomAccessFile: How do I Clear the txt file and write multiple lines of..

807569Jul 14 2006 — edited Jul 23 2006
Hello all,
I am a 6th grade teacher and am taking a not so "Advanced Java Programming" class. Could someone please help me with the following problem.

I am having trouble with RandomAccessFile.

What I want to do is:
1. Write multiple lines of text to a file
2. Be able to delete previous entries in the file
3. It would also be nice to be able to go to a certian line of text but not manditory.
import java.io.*;
public class Logger
{
RandomAccessFile raf;
public Logger()
	{
	try
		{
		raf=new RandomAccessFile("default.txt","rw");
		raf.seek(0);
		raf.writeBytes("");
		}
	catch(Exception e)
		{
		e.printStackTrace();
		}
	}
public Logger(String fileName)
	{
	try
		{
		raf=new RandomAccessFile(fileName,"rw");
		raf.seek(0);
		raf.writeBytes("");
		}
	catch(Exception e)
		{
		e.printStackTrace();
		}
	}

public void writeLine(String line)
	{
	try
		{

		long index=0;
		raf.seek(raf.length());		
		raf.writeBytes(index+" "+line);
		}
	catch(Exception e)
		{
		e.printStackTrace();
		}		
	}

public void closeFile()
	{
	try
		{
		raf.close();
		}
	catch(Exception e)
		{
		e.printStackTrace();
		}
	}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 20 2006
Added on Jul 14 2006
8 comments
1,040 views