Java examples for java.io:InputStream Read
Get string from binary stream.
//package com.java2s; import java.io.IOException; import java.io.InputStream; public class Main { /**/*from w w w . j ava2 s . c o m*/ * Get string from binary stream. >So, if len < 0x7F, it is encoded on one * byte as b0 = len >if len < 0x3FFF, is is encoded on 2 bytes as b0 = (len * & 0x7F) | 0x80, b1 = len >> 7 >if len < 0x 1FFFFF, it is encoded on 3 * bytes as b0 = (len & 0x7F) | 0x80, b1 = ((len >> 7) & 0x7F) | 0x80, b2 = * len >> 14 etc. * * @param is * @return * @throws IOException */ public static String getString(final InputStream is) throws IOException { int val = getStringLength(is); // System.out.println("d:" + val); byte[] buffer = new byte[val]; if (is.read(buffer) < 0) { throw new IOException("EOF"); } return new String(buffer); } /** * Binary files are encoded with a variable length prefix that tells you * the size of the string. The prefix is encoded in a 7bit format where the * 8th bit tells you if you should continue. If the 8th bit is set it means * you need to read the next byte. * @param bytes * @return */ public static int getStringLength(final InputStream is) throws IOException { int count = 0; int shift = 0; boolean more = true; while (more) { byte b = (byte) is.read(); count |= (b & 0x7F) << shift; shift += 7; if ((b & 0x80) == 0) { more = false; } } return count; } }