import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class HttpResponseBuffer {
private final InputStream inputStream;
private final BufferedReader reader;
private final List<String> bufferedLines = new ArrayList<>();
private final int bufferSize;
/**
* Constructor for the HttpResponseBuffer.
* @param inputStream The input stream from the HTTP response.
* @param bufferSize The maximum number of lines to buffer.
*/
public HttpResponseBuffer(InputStream inputStream, int bufferSize) {
this.inputStream = inputStream;
this.reader = new BufferedReader(new InputStreamReader(inputStream));
this.bufferSize = bufferSize;
}
/**
* Reads and buffers lines from the input stream.
* @return The next line from the input stream, or null if the stream is closed.
*/
public String readLine() {
try {
if (bufferedLines.isEmpty()) {
String line = reader.readLine();
if (line == null) {
return null; // End of stream
}
bufferedLines.add(line);
//If buffer is full, remove the first line
if (bufferedLines.size() > bufferSize) {
bufferedLines.remove(0);
}
return line;
} else {
String line = bufferedLines.remove(0); // Get the oldest line in the buffer
bufferedLines.add(line); // Add the line to the end of the buffer
return line;
}
} catch (IOException e) {
// Handle IO exceptions (e.g., stream closed)
return null; // Or re-throw if appropriate
}
}
/**
* Returns a list of all buffered lines.
* @return A list of strings, each representing a buffered line.
*/
public List<String> getBufferedLines() {
return new ArrayList<>(bufferedLines); // Return a copy to prevent external modification
}
/**
* Closes the input stream.
*/
public void close() {
try {
reader.close();
inputStream.close();
} catch (IOException e) {
// Handle IO exceptions during closing
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
//Example Usage
try (InputStream inputStream = System.in) {
HttpResponseBuffer buffer = new HttpResponseBuffer(inputStream, 5); //Buffer size of 5 lines
for (int i = 0; i < 10; i++) {
String line = buffer.readLine();
if (line != null) {
System.out.println("Read: " + line);
} else {
System.out.println("End of stream");
break;
}
}
buffer.close();
}
}
}
Add your comment