Java 基础 inputStream.read(bufferBytes) 读取文本错乱、异常、不全

...
 byte[] bufferBytes = new byte[1024];
        StringBuffer stringBuilder = new StringBuffer();
        try {
            int length = 0;
            while ((length = inputStream.read(bufferBytes)) != -1) {
                stringBuilder.append(new String(bufferBytes));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
     ...

之前读小文件没啥问题,就这么用了,今天读json文件比较大的在读取的时候出现问题了

原因:因为每次 while 循环后 bufferBytes 不会清空,仍然会存在缓存上一次的数据,如果直接 bufferBytes 整个拿来 append 用,数据就错乱了,所以必须要拿每次真实读到的内容进行使用,或者套一层 BufferedReader 进行处理

  • 方法1:append 时候紧跟上指定长度
...
 byte[] bufferBytes = new byte[1024];
        StringBuffer stringBuilder = new StringBuffer();
        try {
            int length = 0;
            while ((length = inputStream.read(bufferBytes)) != -1) {
                stringBuilder.append(new String(bufferBytes, 0, length));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
     ...
  • 方法二:采用 bufferedReader.readLine 方式去读
try {
            fileInputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(fileInputStream);
            bufReader = new BufferedReader(inputStreamReader);
            String line = "";
            while ((line = bufReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
           
        }

你可能感兴趣的:(Java 基础 inputStream.read(bufferBytes) 读取文本错乱、异常、不全)