Java File Read via ByteBuffer readUtf8(DataInput in)

Here you can find the source of readUtf8(DataInput in)

Description

Safely reads a string as UTF-8 from a byte stream.

License

LGPL

Parameter

Parameter Description
in The stream

Exception

Parameter Description
IOException In case of a reading or decoding error

Return

The string

Declaration

public static String readUtf8(DataInput in) throws IOException 

Method Source Code

//package com.java2s;
/**/*  w ww .j  av  a 2s .  com*/
 * Copyright 2009-2016 Three Crickets LLC.
 * <p>
 * The contents of this file are subject to the terms of the LGPL version 3.0:
 * http://www.gnu.org/copyleft/lesser.html
 * <p>
 * Alternatively, you can obtain a royalty free commercial license with less
 * limitations, transferable or non-transferable, directly from Three Crickets
 * at http://threecrickets.com/
 */

import java.io.DataInput;

import java.io.IOException;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class Main {
    /**
     * UTF-8 charset.
     */
    private static final Charset UTF8 = Charset.forName("UTF-8");

    /**
     * Safely reads a string as UTF-8 from a byte stream.
     * <p>
     * Unlike {@link DataInput#readUTF()}, this implementation does not limit
     * the string size.
     * 
     * @param in
     *        The stream
     * @return The string
     * @throws IOException
     *         In case of a reading or decoding error
     * @see #writeUtf8(DataOutput, String)
     * @see #decodeUtf8(byte[])
     */
    public static String readUtf8(DataInput in) throws IOException {
        byte[] bytes = new byte[in.readInt()];
        in.readFully(bytes);
        return decodeUtf8(bytes);
    }

    /**
     * Safely decodes a UTF-8-encoded string.
     * 
     * @param bytes
     *        The bytes
     * @return The string
     */
    public static String decodeUtf8(byte[] bytes) {
        return UTF8.decode(ByteBuffer.wrap(bytes)).toString();
    }
}

Related

  1. readUint32(final DataInput di)
  2. readUint32AsInt(DataInput di)
  3. readUintLE(byte[] bytes, int pointer, int size)
  4. readUnsignedInt(InputStream is)
  5. readUnsignedInt24(InputStream is)
  6. readVarLong(byte[] arr)
  7. readWaveFile44100_16Bit_Mono(String dir, String name)
  8. readWavHeader(DataInputStream inStrm, FileChannel fc)
  9. readWholeFile(File file, StringBuilder stringBuilder)