從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