{
chf = File.createTempFile("jcrvdedit", null, tempDirectory);
chch = new RandomAccessFile(chf, "rw").getChannel();
// allocate the space for whole file
MappedByteBuffer bb = chch.map(FileChannel.MapMode.READ_WRITE, position + length, 0);
bb.force();
bb = null;
ReadableByteChannel bch = Channels.newChannel(new ByteArrayInputStream(this.data));
if ((newIndex = (int)position) > 0)
{
// begin from the existed bytes
chch.transferFrom(bch, 0, newIndex < data.length ? newIndex : data.length);
bch.close();
}
// write update data
// TODO don't use Channels.newChannel in Java5
ReadableByteChannel sch = Channels.newChannel(stream);
chch.transferFrom(sch, newIndex, length);
sch.close();
newIndex += length;
if (newIndex < data.length)
// write the rest of existed data
chch.transferFrom(bch, newIndex, data.length - newIndex);
bch.close();
}
catch (final IOException e)
{
try
{
chch.close();
chf.delete();
}
catch (Exception e1)
{
}
throw new IOException("update error " + e.getMessage())
{
@Override
public Throwable getCause()
{
return e;
}
};
}
this.spoolFile = chf;
this.spoolChannel = chch;
this.data = null;
}
}
else
{
MappedByteBuffer bb = spoolChannel.map(FileChannel.MapMode.READ_WRITE, position, length);
ReadableByteChannel ch = Channels.newChannel(stream);
ch.read(bb);
ch.close();
bb.force();
}
}