Java ByteBuffer Read readNullTerminatedString(ByteBuffer buf)

Here you can find the source of readNullTerminatedString(ByteBuffer buf)

Description

read Null Terminated String

License

Open Source License

Declaration

public static String readNullTerminatedString(ByteBuffer buf) 

Method Source Code

//package com.java2s;
/**// w  ww.ja va2 s  .  com
 * Project: ${puma-common.aid}
 * <p/>
 * File Created at 2012-6-6 $Id$
 * <p/>
 * Copyright 2010 dianping.com. All rights reserved.
 * <p/>
 * This software is the confidential and proprietary information of Dianping
 * Company. ("Confidential Information"). You shall not disclose such
 * Confidential Information and shall use it only in accordance with the terms
 * of the license agreement you entered into with dianping.com.
 */

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

public class Main {
    public static final String UTF_8 = "UTF-8";

    public static String readNullTerminatedString(ByteBuffer buf) {
        return readNullTerminatedString(buf, UTF_8);
    }

    public static String readNullTerminatedString(ByteBuffer buf, String encoding) {
        int start = buf.position();
        int len = 0;

        int maxLen = buf.limit();

        while ((buf.position() < maxLen) && (buf.get() != 0)) {
            len++;
        }

        try {
            return new String(buf.array(), start, len, encoding);
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }
}

Related

  1. readKatakana(ByteBuffer b, char s[], int off, int len)
  2. readLen(ByteBuffer dup, int nls)
  3. readLink(ByteBuffer bb)
  4. readLink(ByteBuffer bb)
  5. readNewLine(ByteBuffer buf)
  6. readObject(ByteBuffer byteBuffer)
  7. readReal(ByteBuffer bb)
  8. readResBit15(ByteBuffer fromBuffer)
  9. readShortLE(ByteBuffer buf, int i)