1

I am trying to check whether a certain position in RandomAcceessFile is empty in order to avoid overwriting some data before writing in the file. I initialized a very large RandomAccessFile:

randAccFile = new RandomAccessFile( DIR + "/" + FILENAME, "rw" );
randAccFile.setLength(LARGE_SIZE);

Then I have this method to check whether a given position is Empty, let's say pointer is set to 20:

randAccFile.seek(pointer);
byte[] data = new byte[BLOCK_SIZE];
randAccFile.readFully(data);

Afterwards, I am trying to check emptiness by trimming the data and seeing whether the length of resulting string is 0. Before I get to that point readFully() throws

java.io.EOFException
        at java.base/java.io.RandomAccessFile.readFully(RandomAccessFile.java:474)
        at java.base/java.io.RandomAccessFile.readFully(RandomAccessFile.java:448)

I wonder if the RandomAccessFile was not initialized in the right way, or if I am not allowed to readFully from part of it that wasn't filled up yet. I also wonder if there is a better way of checking whether the RandomAccessFile is empty certain position. It is surprising that I get EOF exception since the length of the file is much larger than the offset at which I am trying to read + the block size. In my program it might happen that there will be parts that remain empty forever and that there will be chunks of data written after it since I am not writing and reading from it sequentially.

Any suggestions welcome.

vcucu
  • 184
  • 3
  • 12
  • 1
    To clarify, (a) `LARGE_SIZE` is larger than the current file size? And (b) `pointer` is larger than the current file size and smaller than `pointer`? And `pointer + BLOCK_SIZE` is smaller than `LARGE_SIZE`? If so, how are you verifying that this is indeed the case? – Konrad Rudolph Feb 04 '20 at 11:21
  • Are you sure that converting your byte[] to a String and trimming is the best solution here? Not all files are strictly deserializable to plain text; you may be better off simply adding in known markers in your file or seeing if `RandomAccessFile` provides some way to check for if the data range is written. – Austin Schaefer Feb 04 '20 at 11:52
  • Please provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) so that we can be sure we understand what you are doing. – Stephen C Feb 04 '20 at 13:16
  • I am not sure what do you mean by current file size, because the current file size is the LARGE_SIZE as soon as I set it to be so. pointer+BLOCK_SIZE is definitely smaller than LARGE_SIZE, I hardcoded them, for now, to be sure and the exception is still thrown. I am not sure about checking the emptiness in this way, I changed it to randAccFile.read() == 0 and that seems to work. – vcucu Feb 04 '20 at 14:22

0 Answers0