Reads a null-terminated ('\0') string from the provided ByteBuffer. - Java java.nio

Java examples for java.nio:ByteBuffer Read

Description

Reads a null-terminated ('\0') string from the provided ByteBuffer.

Demo Code


//package com.java2s;
import java.nio.ByteBuffer;

public class Main {
    /**//w ww.  ja va2 s .  c o m
     * Reads a null-terminated (<code>'\0'</code>) string from the provided
     * buffer. No checks are made to prevent underflow.
     * 
     * @param buf
     *            the buffer to read the string from.
     * @return the string.
     */
    public static String getString(ByteBuffer buf) {
        StringBuilder builder = new StringBuilder();
        for (char c; (c = (char) buf.get()) != '\0';) {
            builder.append(c);
        }
        return builder.toString();
    }
}

Related Tutorials