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

voidwriteLong(RandomAccessFile raFile, long num)
write Long
ByteBuffer bb = ByteBuffer.allocate(8);
bb.putLong(num);
raFile.write(bb.array());
ByteBufferwriteObject(Serializable serializable)
write Object
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
try {
    bos = new ByteArrayOutputStream();
    oos = new ObjectOutputStream(new BufferedOutputStream(bos));
    oos.writeObject(serializable);
} finally {
    if (oos != null) {
...
voidwriteShort(int i, DataOutput out)
write Short
ByteBuffer bb = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN);
bb.putShort((short) i);
out.write(bb.array());
voidwriteString(ByteArrayOutputStream bout, String val)
write String
if (val == null) {
    writeInt(bout, -1);
    return;
if (val.length() == 0) {
    writeInt(bout, 0);
    return;
byte[] bytes = val.getBytes(ENCODING);
writeInt(bout, bytes.length);
bout.write(bytes);
voidwriteStringContents(String contents, WritableByteChannel channel)
Writes String contents to channel and closes it.
try {
    ByteBuffer buffer = ByteBuffer.wrap(contents.getBytes(StandardCharsets.UTF_8));
    channel.write(buffer);
} finally {
    channel.close();
voidwriteStringData(DataOutputStream mDataOutputStream, String token)
write String Data
byte[] name = token.getBytes();
mDataOutputStream.write(ByteBuffer.allocate(4).putInt(name.length).array());
mDataOutputStream.flush();
mDataOutputStream.write(name);
mDataOutputStream.flush();
voidwriteStringToSocketChannel(String text, SocketChannel sc)
write String To Socket Channel
text += "\n";
try {
    ByteBuffer buf = charset.encode(text);
    while (buf.hasRemaining()) {
        sc.write(buf);
} catch (Exception ex) {
    ex.printStackTrace();
...
voidwriteToFile(String path, ByteOrder byteOrder)
write To File
String fileName = "My new STL";
File file = new File(path);
DataOutputStream output = null;
try {
    output = new DataOutputStream(new FileOutputStream(path));
    byte[] fileNameByteArray = fileName.getBytes();
    ByteBuffer buffer = ByteBuffer.allocate(500);
    buffer.order(byteOrder);
...
voidwriteUtf8(DataOutput out, String string)
Safely writes a string in UTF-8 to a byte stream.
if (string == null)
    out.writeInt(0);
else {
    byte[] bytes = encodeUtf8(string);
    out.writeInt(bytes.length);
    out.write(bytes);
voidwriteVector(DataOutputStream output, float[] vector)
write Vector
ByteBuffer buffer = ByteBuffer.allocate(vector.length * Float.BYTES);
FloatBuffer floatBuffer = buffer.asFloatBuffer();
floatBuffer.put(vector);
output.write(buffer.array());