Read a line of text from an input stream in Java keeping the line-termination character(s)

前端 未结 1 1658
情深已故
情深已故 2021-02-19 12:56

I have this code in Java:

InputStreamReader isr = new InputStreamReader(getInputStream());
BufferedReader ir = new BufferedReader(isr);
String line;
while ((line         


        
相关标签:
1条回答
  • 2021-02-19 13:25

    If you want to read a HTTP POST request, I strongly suggest using BufferedInputStream.read() (not BufferedReader!) directly (without readLine-like intermediate abstractions), paying attention to all details manually, including the handling of CR and LF according to the HTTP RFC.

    Here is my answer to your more specific question (how to implement exactly that readLine). This might not be the fastest solution, but it's time complexity is optimal, and it works:

    import java.io.BufferedReader;
    import java.io.IOException;   
    public class LineReader {   
      private int i = -2;
      private BufferedReader br;
      public OriginalLineReader(BufferedReader br) { this.br = br; }
      public String readLine() throws IOException {
        if (i == -2) i = br.read();
        if (i < 0) return null;
        StringBuilder sb = new StringBuilder();
        sb.append((char)i);
        if (i != '\r' && i != '\n') {
          while (0 <= (i = br.read()) && i != '\r' && i != '\n') {
            sb.append((char)i);
          }
          if (i < 0) return sb.toString();
          sb.append((char)i);
        }
        if (i == '\r') {
          i = br.read();
          if (i != '\n') return sb.toString(); 
          sb.append((char)'\n');
        }
        i = -2;
        return sb.toString();
      }
    }
    

    You won't find such a readLine built into Java. It's likely that you will find similar, but not exactly matching readLines in a third-party .jar file. My recommendation is just to use the one above, if you really need that feature.

    0 讨论(0)
提交回复
热议问题