Java ByteBuffer to String readString(ByteBuffer bb, int limit)

Here you can find the source of readString(ByteBuffer bb, int limit)

Description

Reads a null-terminated string from the current position of the given bytebuffer.

License

Creative Commons License

Parameter

Parameter Description
bb ByteBuffer to read from
limit The maximum number of characters to read before giving up.

Return

The ASCII string that was found

Declaration

public static String readString(ByteBuffer bb, int limit) 

Method Source Code

//package com.java2s;
/**/*from w w w . ja  v a 2 s.  c  om*/
 * Copyright (C) 2011 Darien Hager
 *
 * This code is part of the "HL2Parse" project, and is licensed under
 * a Creative Commons Attribution-ShareAlike 3.0 Unported License. For
 * either a summary of conditions or the full legal text, please visit:
 *
 * http://creativecommons.org/licenses/by-sa/3.0/
 *
 * Permissions beyond the scope of this license may be available
 * at http://technofovea.com/ .
 */

import java.nio.ByteBuffer;

import java.util.Arrays;

public class Main {
    /**
     * The null byte terminator used in C-style strings
     */
    public static final int NULL_TERMINATOR = 0x00;

    /**
     * Reads a null-terminated string from the current position of the given bytebuffer.
     * @param bb ByteBuffer to read from
     * @param limit The maximum number of characters to read before giving up.
     * @return The ASCII string that was found
     */
    public static String readString(ByteBuffer bb, int limit) {
        int max = Math.min(limit, bb.remaining());
        byte[] name = new byte[max];
        bb.get(name);
        return readString(name, max);
    }

    /**
     * Reads a null-terminated string from the current position of the given byte array.
     * @param buf ByteBuffer to read from
     * @param limit The maximum number of characters to read before giving up.
     * @return The ASCII string that was found
     */
    public static String readString(byte[] buf, int limit) {
        int max = Math.min(limit, buf.length);
        int firstnull = max;
        for (int i = 0; i < buf.length; i++) {
            if (buf[i] == NULL_TERMINATOR) {
                firstnull = i;
                break;

            }
        }
        return new String(Arrays.copyOf(buf, firstnull));
    }
}

Related

  1. readStr(ByteBuffer bb, int off, int len)
  2. readString(byte[] tmp, ByteBuffer in)
  3. readString(ByteBuffer b, char s[], int off, int len)
  4. readString(ByteBuffer bb)
  5. readString(ByteBuffer bb)
  6. readString(ByteBuffer buf)
  7. readString(ByteBuffer buf, int length)
  8. readString(ByteBuffer buff)
  9. readString(ByteBuffer buff, int len)