java 从InputStream 获取字节数组_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java 从InputStream 获取字节数组

java 从InputStream 获取字节数组

 2013/8/11 16:07:17  hw1287789687  程序员俱乐部  我要评论(0)
  • 摘要:java中,如何从InputStream读取字节数组呢?方式一:/****Hasbeentested**@paramin*@return*@throwsIOException*/publicstaticbyte[]readBytes(InputStreamin)throwsIOException{byte[]temp=newbyte[in.available()];byte[]result=newbyte[0];intsize=0;while((size=in.read(temp))!=-1)
  • 标签:数组 Java

java 中,如何从InputStream 读取字节数组呢?

方式一:

class="java" name="code">/***
	 * 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;
	}

?

发表评论
用户名: 匿名