read String from DataInputStream - Java java.io

Java examples for java.io:DataInputStream

Description

read String from DataInputStream

Demo Code


//package com.java2s;
import java.io.DataInputStream;

import java.io.IOException;

public class Main {
    public static String readString(DataInputStream in) throws IOException {
        // Read the number of bytes.
        short length = in.readShort();
        if (length == 0)
            return "";

        // Allocate an array of bytes.
        byte[] bytes = new byte[length];

        // Read the array.
        in.readFully(bytes);/*w  ww.jav a  2s .c o m*/

        // Convert the array to a string.
        return new String(bytes, "UTF-8");
    }
}

Related Tutorials