BufferedReader for large ByteBuffer?

后端 未结 3 1245
悲哀的现实
悲哀的现实 2021-01-20 05:37

Is there a way to read a ByteBuffer with a BufferedReader without having to turn it into a String first? I want to read through a fairly large ByteBuffer as lines of text an

3条回答
  •  臣服心动
    2021-01-20 05:57

    You can use NIO, but there's no real need here. As Jon Skeet suggested:

    public byte[] read(InputStream istream)
    {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      byte[] buffer = new byte[1024]; // Experiment with this value
      int bytesRead;
    
      while ((bytesRead = istream.read(buffer)) != -1)
      {
        baos.write(buffer, 0, bytesRead);
      }
    
      return baos.toByteArray();
    }
    
    
    // after the process is run, we call this method with the String
    public void readLines(byte[] data)
    {
      BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data)));
      String line;
    
      while ((line = reader.readLine()) != null)
      {
        // do stuff with line
      }
    }
    

提交回复
热议问题