I have this code in Java:
InputStreamReader isr = new InputStreamReader(getInputStream());
BufferedReader ir = new BufferedReader(isr);
String line;
while ((line
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 readLine
s in a third-party .jar
file. My recommendation is just to use the one above, if you really need that feature.