Java String Decode decodeStringFromByteArray(byte[] data)

Here you can find the source of decodeStringFromByteArray(byte[] data)

Description

Decodes a string object from the given byte array.

License

Open Source License

Parameter

Parameter Description
data The byte array or <code>null</code>.

Return

The decoded string or null.

Declaration

public static String decodeStringFromByteArray(byte[] data) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2011, 2014 Wind River Systems, Inc. and others. All rights reserved.
 * This program and the accompanying materials are made available under the terms
 * of the Eclipse Public License v1.0 which accompanies this distribution, and is
 * available at http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/* ww w.  ja  va 2s  .co m*/
 * Wind River Systems - initial API and implementation
 *******************************************************************************/

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    /**
     * Decodes a string object from the given byte array.
     * <p>
     * Used if services sends plain strings instead of encoding them through JSON.
     *
     * @param data The byte array or <code>null</code>.
     * @return The decoded string or <code>null</code>.
     */
    public static String decodeStringFromByteArray(byte[] data) {
        String args = null;
        if (data != null) {
            StringBuilder builder = new StringBuilder();
            InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(data));
            try {
                int c = reader.read();
                while (c != -1) {
                    builder.append(c != 0 ? Character.valueOf((char) c).charValue() : ' ');
                    c = reader.read();
                }
            } catch (IOException ex) {
                /* ignored on purpose */ }

            if (builder.length() > 0)
                args = builder.toString().trim();
        }
        return args;
    }
}

Related

  1. decodeString(String s, String charset)
  2. decodeString(String s, String encoding)
  3. decodeString(String str)
  4. decodeString(String str)
  5. decodeString(StringReader in)
  6. decodeStrings(byte[] stringBytes)
  7. decodeText(String encodeText)
  8. decodeText(String s)
  9. decodeText(String str)