Reads a .NET String from the InputStream and returns it as a Java String. - Java java.io

Java examples for java.io:InputStream Read

Description

Reads a .NET String from the InputStream and returns it as a Java String.

Demo Code


//package com.java2s;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    /**//from   w w  w  .  j av  a2s .  co  m
     * Reads a .NET String from the stream and returns it as a Java String.
     * @param in The input stream
     * @return A String as a Java String
     * @throws IOException If an IO error occurs
     */
    public static String readString(final InputStream in)
            throws IOException {
        int length = read7BitEncodedInt(in);

        byte[] buffer = new byte[length];

        if (in.read(buffer) < 0)
            throw new EOFException();

        //System.out.printf("String: (Length: %s)\n", length);
        //printBytes(buffer);

        return new String(buffer);
    }

    /**
     * Reads the integer from the stream as a 7 bit encoded integer
     * @param in The input stream
     * @return The integer read
     * @throws IOException If an IO error occurs
     */
    public static int read7BitEncodedInt(final InputStream in)
            throws IOException {
        //Based on the .NET implementation.  See http://referencesource.microsoft.com/#mscorlib/system/io/binaryreader.cs,569

        //Read out an Int32 7 bits at a time.  The high bit of the byte when on means to continue reading more bytes.
        int count = 0;
        int shift = 0;
        byte b;

        do {
            //Check for a corrupted stream.  Read a max of 5 bytes.
            if (shift == 5 * 7) //5 bytes max per Int32, shift += 7
                throw new IOException("Bad 7 bit encoded integer");

            byte[] bArray = new byte[1];
            if (in.read(bArray) < 0)
                throw new EOFException();

            b = bArray[0];

            //b = (byte) in.read();

            //if (b < 0) //in.read() returns -1 if no bytes were read
            //    throw new EOFException();

            count |= (b & 0x7F) << shift;
            shift += 7;
        } while ((b & 0x80) != 0);

        return count;
    }
}

Related Tutorials