Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete The First Bytes of a Random Access File in Java

Tags:

java

file-io

I'm writing bytes to a random access file. After completing the operation, I want to delete the first 100 bytes from the file. How can I achieve this?

Thanks in advance.

like image 650
sirin Avatar asked Dec 02 '10 14:12

sirin


People also ask

How do I get rid of RandomAccessFile?

RandomAccessFile temp = new RandomAccessFile ("temp. tmp", "rw"); temp = new File(NetSimView. filename); temp. delete();

What is the use of RandomAccessFile in Java?

Java RandomAccessFile provides the facility to read and write data to a file. RandomAccessFile works with file as large array of bytes stored in the file system and a cursor using which we can move the file pointer position.

What is RandomAccessFile?

A random access file behaves like a large array of bytes stored in the file system. There is a kind of cursor, or index into the implied array, called the file pointer; input operations read bytes starting at the file pointer and advance the file pointer past the bytes read.

How do you delete a record in Java?

delete() method. In Java, we can delete a file by using the File. delete() method of File class. The delete() method deletes the file or directory denoted by the abstract pathname.


2 Answers

i found a method which provides the desired works. it's deleteRAF and here.

thanks your advices.

like image 154
sirin Avatar answered Sep 19 '22 03:09

sirin


AFAIK, you will need to copy the remaining bytes (file length - 100) to a new file. Deleting the first 100 bytes from a file is not possible without copying the remaining bytes to a new file.

Edit: As cdhowie rightly pointed out, you could:

  • seek to 100,
  • read X amount of bytes (more than 100 though)
  • seek to 0,
  • write X amount of bytes

Then repeat the process until the entire file is written. Finish off by setting the filelength 100 bytes less than previously. If you want to be on the safe side and not risk corrupting the original file, it could be worth writing to a temp file first.

like image 30
BlueVoodoo Avatar answered Sep 23 '22 03:09

BlueVoodoo