문제

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?

도움이 되었습니까?

해결책

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) {
    }
}

다른 팁

You can fix it this way

FileChannel fc = FileChannel.open(getFile().toPath(), StandardOpenOption.APPEND);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top