Search code examples
javabytebufferfileoutputstreamcorruptfilechannel

Writing data to file is erasing everything before it(Placing 00's) and changing the file size


I have a program which writes out some data- I am using this logic

FileOutputStream outpre = new FileOutputStream(getfile());
FileChannel ch = outpre.getChannel();
ch.position(startwr);
ch.write(ByteBuffer.wrap(dsave));
outpre.close();

It writes out the correct data to the correct location, the only problem is that everything before the starting location to write (startwr) gets replaced with 00's, and the file is also changed making the point at which the writing was done, the end of the file.

How can I write data to the file without corrupting the previous data and changing the file size?


Solution

  • You need to instruct the stream to either append or overwrite the contents of the file...

    Take a look at FileOutpuStream(File, boolean) for more details

    Updated

    After some mucking around, I found that the only solution I could get close to working was...

    RandomAccessFile raf = null;
    
    try {
        raf = new RandomAccessFile(new File("C:/Test.txt"), "rw");
        raf.seek(3);
        raf.writeBytes("BB");
    } catch (IOException exp) {
        exp.printStackTrace();
    } finally {
        try {
            raf.close();
        } catch (Exception e) {
        }
    }