Create a basic string from bytes. - Java java.lang

Java examples for java.lang:byte Array to String

Description

Create a basic string from bytes.

Demo Code

//package com.java2s;

public class Main {
    /**/*  w  w  w .  j  a  va2 s. c  o m*/
     * Create a basic string from bytes. This is effectively the byte array
     * cast to a char array and turned into a String.
     * @param bytes the source of the bytes for the basic string
     * @param offset the offset into butes where the string starts
     * @param length the number of bytes to turn into a string
     * @return the corresponding string
     */
    public static String asBasicString(byte[] bytes, int offset, int length) {
        final char[] c = new char[length];
        for (int i = 0; i < c.length; ++i) {
            c[i] = (char) bytes[i + offset];
        }
        return new String(c);
    }

    /**
     * Create a basic string from bytes. This is effectively the byte array
     * cast to a char array and turned into a String.
     * @param bytes the bytes, all of which are used
     * @return the corresponding string
     */
    public static String asBasicString(byte[] bytes) {
        return asBasicString(bytes, 0, bytes.length);
    }
}

Related Tutorials