从InputStream中读取特定长度的数据


	public static final int READ_BUFFER_SIZE = 1024;
	/**
	 * 读取流中的字符到数组
	 * @param in 该方法执行完成不会关闭流
	 * @param limit 读取大小限制
	 * @return
	 * @throws IOException
	 */
	public static byte[] readStreamAsByteArray(InputStream in, int limit) throws IOException {

		if (in == null) {
			return new byte[0];
		}

		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[READ_BUFFER_SIZE];
		int len = -1;
		int temp = limit - READ_BUFFER_SIZE;
		while ((len = in.read(buffer)) != -1) {
			output.write(buffer, 0, len);
			if(output.size() > temp) {
				if(output.size() == limit) {
					break;
				}

				byte[] buffer2 = new byte[limit - output.size()];
				while ((len = in.read(buffer2)) != -1) {
					output.write(buffer2, 0, len);
					if(output.size() == limit) {
						break;
					}
					buffer2 = new byte[limit - output.size()];
				}
				
				break;
			}
		}
		return output.toByteArray();
	}

  上面代码用于从InputStream中读取特定长度的数据,把文件分断处理时用到


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM