Java 中如何从InputStream中读取指定长度的字节呢?
代码如下:
- /***
- * 从输入流获取字节数组,当文件很大时,报java.lang.OutOfMemoryError: Java heap space
- *
- * @since 2014-02-19
- * @param br_right
- * @param length2
- * @return
- * @throws IOException
- */
- public static byte[] readBytesFromInputStream(InputStream br_right,
- int length2) throws IOException {
- int readSize;
- byte[] bytes = null;
- bytes = new byte[length2];
- long length_tmp = length2;
- long index = 0;// start from zero
- while ((readSize = br_right.read(bytes, (int) index, (int) length_tmp)) != -1) {
- length_tmp -= readSize;
- if (length_tmp == 0) {
- break;
- }
- index = index + readSize;
- }
- return bytes;
- }
- /***
- * 读取指定长度的字节
- * @since 2014-02-27
- * @param ins
- * @param sumLeng : 要读取的字节数
- * @return
- * @throws IOException
- */
- public static byte[]readBytesFromGzipInputStream(GZIPInputStream ins,long sumLeng) throws IOException{
- byte[] fileNameBytes = new byte[(int) sumLeng];
- int fileNameReadLength=0;
- int hasReadLength=0;//已经读取的字节数
- while((fileNameReadLength=ins.read(fileNameBytes,hasReadLength,(int)sumLeng-hasReadLength))>0){
- hasReadLength=hasReadLength+fileNameReadLength;
- }
- return fileNameBytes;
- }
- /***
- * read char array from inputstream according to specified length.
- *
- * @param file
- * @param ins
- * @param length2
- * :要读取的字符总数
- * @throws IOException
- */
- public static char[] getCharsFromInputStream(BufferedReader br_right,
- int length2) throws IOException {
- int readSize;
- char[] chars = null;
- chars = new char[length2];
- long length_tmp = length2;
- long index = 0;// start from zero
- while ((readSize = br_right.read(chars, (int) index, (int) length_tmp)) != -1) {
- length_tmp -= readSize;
- if (length_tmp == 0) {
- break;
- }
- index = index + readSize;// 写入字符数组的offset(偏移量)
- }
- return chars;
- }
- /***
- * 从文件中读取指定长度的字符(注意:不是字节)
- *
- * @param file
- * @param length2
- * @return
- * @throws IOException
- */
- public static char[] getCharsFromFile(File file, int length2)
- throws IOException {
- FileInputStream fin = new FileInputStream(file);
- InputStreamReader inr = new InputStreamReader(fin);
- BufferedReader br = new BufferedReader(inr);
- return getCharsFromInputStream(br, length2);
- }
- private static byte[] readDataFromLength(HttpURLConnection huc,
- int contentLength) throws Exception {
- InputStream in = huc.getInputStream();
- BufferedInputStream bis = new BufferedInputStream(in);
- // 数据字节数组
- byte[] receData = new byte[contentLength];
- // 已读取的长度
- int readAlreadyLength = 0;
- // while ((readAlreadyLength+= bis.read(receData, readAlreadyLength,
- // contentLength-readAlreadyLength))< contentLength) {
- // System.out.println("right");
- // }
- while ((readAlreadyLength = readAlreadyLength
- + bis.read(receData, readAlreadyLength, contentLength
- - readAlreadyLength)) < contentLength) {
- }
- // System.out.println("readLength=" + readLength);
- return receData;
- }
参考我的另外一篇博客:http://hw1287789687.iteye.com/blog/2019425
时间: 2024-12-01 01:28:26