javafile-handlingjava-ioseekrandomaccessfile

seek() method not working with InputStream available() method in java


I am working on this java problem, where I have to write to a text file on the system without tempering existing text data on that file, I am using randomAceessFile.seek((inputStream.available()+1)); to point my pointer 1 space ahead of existing data, then I have used randomAceessFile.write((newData.trim()).getBytes()); to write to that file, now the problem is that after this operation file data should have space between existing data and new data that is added, but code below only added new data to file and \00 instead of spaces in-between data.

import java.io.RandomAccessFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class Random{
    public static void main(String[] args) {
        try {
            File file = new File("data.txt");
            InputStream inputStream = new FileInputStream(file);
            RandomAccessFile randomAceessFile = new RandomAccessFile(file, "rw");
            randomAceessFile.seek((inputStream.available()+1));
            String newData = "new data on file";
            randomAceessFile.write((newData.trim()).getBytes());
            randomAceessFile.close();
            inputStream.close();
        } catch (Exception e) {
            System.err.println(e.getCause());
            System.out.println(e.getStackTrace());
            System.out.println(e.getMessage());
        }
    }
}

The output given by this program is

existing data \00new data on file


Solution

  • The zero byte is because you seek to the exiting length plus one. The existing bytes are numbered 0 to length-1, so you want to seek to exactly the existing length.

    That is, nothing is specifically written to the file at offset 'existing length', so you get a zero byte.

    No-one is going to magically insert a space (0x20 byte) that wasn't there before. You need to do it. This is easy: newData = " new data on file" (and omit the trim call on what you are writing).

    Perhaps what you were reading before was using the word 'space' in the sense of 'position' ?