Java tutorial
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.io.InputStream; public class Main { public static final String readFix(InputStream in, int fix) throws IOException { if (fix <= 0) return null; byte[] bb = new byte[fix]; stmTryRead(in, bb, fix); return new String(bb); } /** * read fix length bytes from inputstream * * @param in * @param fix * @return * @throws IOException */ public static final String readFix(InputStream in, int fix, String charset) throws IOException { if (fix <= 0) return null; byte[] bb = new byte[fix]; stmTryRead(in, bb, fix); return new String(bb, charset); } public static final int stmTryRead(InputStream in, byte[] bb) throws IOException { if ((in == null) || (bb == null) || (bb.length == 0)) return 0; return stmTryRead(in, bb, bb.length); } public static final int stmTryRead(InputStream in, byte[] bb, int len) throws IOException { return stmTryRead(in, bb, 0, len); } public static int stmTryRead(InputStream in, byte[] bb, int off, int len) throws IOException { int r; int l = 0; int t = off; while ((r = in.read(bb, t, len - l)) >= 0) { t += r; l += r; if (l == len) { break; } } return l; } }