Java Utililty Methods File Write via ByteBuffer

List of utility methods to do File Write via ByteBuffer

Description

The list of methods to do File Write via ByteBuffer are organized into topic(s).

Method

MappedByteBuffermmap(File file, long offset, long length, boolean writeable)
mmap
FileChannel chan = channel(file, writeable);
FileChannel.MapMode mode = writeable ? FileChannel.MapMode.READ_WRITE : FileChannel.MapMode.READ_ONLY;
MappedByteBuffer buf = chan.map(mode, offset, length);
chan.close();
return buf;
ByteBuffernewWriteableBuffer(int capacity)
new Writeable Buffer
ByteBuffer newBuffer = ByteBuffer.allocate(capacity);
return newBuffer;
voidwrite(File file, String content, String encoding)
write
FileChannel channel = new FileOutputStream(file).getChannel();
try {
    channel.write(ByteBuffer.wrap(content.getBytes(encoding)));
} finally {
    channel.close();
voidwrite(InputStream source, File target)
Writes an InputStream to disk.
RandomAccessFile file = new RandomAccessFile(target, "rw");
FileChannel channel = null;
FileLock lock = null;
try {
    channel = file.getChannel();
    lock = channel.lock();
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    byte[] bytes = buffer.array();
...
voidwrite(Path file, String content)
write
writeBytes(file, utf8(content));
voidwrite(SeekableByteChannel channel, long start, byte[] bytes)
write
channel.position(start);
ByteBuffer buffer = ByteBuffer.wrap(bytes);
while (buffer.hasRemaining()) {
    channel.write(buffer);
byte[]write24BitInteger(int integer, ByteOrder order)
write Bit Integer
ByteBuffer tmp = ByteBuffer.allocate(4);
tmp.order(order);
tmp.putInt(integer);
if (order == ByteOrder.BIG_ENDIAN) {
    return subArray(tmp.array(), 1, 4);
} else if (order == ByteOrder.LITTLE_ENDIAN) {
    return subArray(tmp.array(), 0, 3);
throw new UnsupportedOperationException("Unknown ByteOrder " + order);
voidwriteByte(WritableByteChannel channel, byte value)
write Byte
channel.write((ByteBuffer) ByteBuffer.allocate(1).put(value).flip());
intwriteBytes(Path file, byte[] bytes)
Writes bytes to a path
FileChannel channel = FileChannel.open(file, EnumSet.of(StandardOpenOption.CREATE,
        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE));
ByteBuffer buffer = ByteBuffer.wrap(bytes);
channel.force(false);
int bytesWritten = channel.write(buffer);
channel.close();
return bytesWritten;
voidwriteComment(File zipFile, String comment)
write Comment
byte[] data = comment.getBytes("utf-8");
final RandomAccessFile raf = new RandomAccessFile(zipFile, "rw");
raf.seek(zipFile.length() - 2);
writeShort(data.length + 2 + COMMENT_SIGN.length, raf);
writeBytes(data, raf);
writeShort(data.length, raf);
writeBytes(COMMENT_SIGN, raf);
raf.close();
...