Java 中,如何从InputStream 读取字节数组呢?
方式一:
- /***
- * Has been tested
- *
- * @param in
- * @return
- * @throws IOException
- */
- public static byte[] readBytes(InputStream in) throws IOException {
- byte[] temp = new byte[in.available()];
- byte[] result = new byte[0];
- int size = 0;
- while ((size = in.read(temp)) != -1) {
- byte[] readBytes = new byte[size];
- System.arraycopy(temp, 0, readBytes, 0, size);
- result = SystemUtil.mergeArray(result,readBytes);
- }
- return result;
- }
方式二:
- public static byte[] readBytes3(InputStream in) throws IOException {
- BufferedInputStream bufin = new BufferedInputStream(in);
- int buffSize = BUFFSIZE_1024;
- ByteArrayOutputStream out = new ByteArrayOutputStream(buffSize);
- // System.out.println("Available bytes:" + in.available());
- byte[] temp = new byte[buffSize];
- int size = 0;
- while ((size = bufin.read(temp)) != -1) {
- out.write(temp, 0, size);
- }
- bufin.close();
- byte[] content = out.toByteArray();
- return content;
- }
依赖的函数:
- /***
- * 合并字节数组
- * @param a
- * @return
- */
- public static byte[] mergeArray(byte[]... a) {
- // 合并完之后数组的总长度
- int index = 0;
- int sum = 0;
- for (int i = 0; i < a.length; i++) {
- sum = sum + a[i].length;
- }
- byte[] result = new byte[sum];
- for (int i = 0; i < a.length; i++) {
- int lengthOne = a[i].length;
- if(lengthOne==0){
- continue;
- }
- // 拷贝数组
- System.arraycopy(a[i], 0, result, index, lengthOne);
- index = index + lengthOne;
- }
- return result;
- }
时间: 2024-11-08 19:36:36