1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. public class HttpResponseBuffer {
  8. private final InputStream inputStream;
  9. private final BufferedReader reader;
  10. private final List<String> bufferedLines = new ArrayList<>();
  11. private final int bufferSize;
  12. /**
  13. * Constructor for the HttpResponseBuffer.
  14. * @param inputStream The input stream from the HTTP response.
  15. * @param bufferSize The maximum number of lines to buffer.
  16. */
  17. public HttpResponseBuffer(InputStream inputStream, int bufferSize) {
  18. this.inputStream = inputStream;
  19. this.reader = new BufferedReader(new InputStreamReader(inputStream));
  20. this.bufferSize = bufferSize;
  21. }
  22. /**
  23. * Reads and buffers lines from the input stream.
  24. * @return The next line from the input stream, or null if the stream is closed.
  25. */
  26. public String readLine() {
  27. try {
  28. if (bufferedLines.isEmpty()) {
  29. String line = reader.readLine();
  30. if (line == null) {
  31. return null; // End of stream
  32. }
  33. bufferedLines.add(line);
  34. //If buffer is full, remove the first line
  35. if (bufferedLines.size() > bufferSize) {
  36. bufferedLines.remove(0);
  37. }
  38. return line;
  39. } else {
  40. String line = bufferedLines.remove(0); // Get the oldest line in the buffer
  41. bufferedLines.add(line); // Add the line to the end of the buffer
  42. return line;
  43. }
  44. } catch (IOException e) {
  45. // Handle IO exceptions (e.g., stream closed)
  46. return null; // Or re-throw if appropriate
  47. }
  48. }
  49. /**
  50. * Returns a list of all buffered lines.
  51. * @return A list of strings, each representing a buffered line.
  52. */
  53. public List<String> getBufferedLines() {
  54. return new ArrayList<>(bufferedLines); // Return a copy to prevent external modification
  55. }
  56. /**
  57. * Closes the input stream.
  58. */
  59. public void close() {
  60. try {
  61. reader.close();
  62. inputStream.close();
  63. } catch (IOException e) {
  64. // Handle IO exceptions during closing
  65. e.printStackTrace();
  66. }
  67. }
  68. public static void main(String[] args) throws IOException {
  69. //Example Usage
  70. try (InputStream inputStream = System.in) {
  71. HttpResponseBuffer buffer = new HttpResponseBuffer(inputStream, 5); //Buffer size of 5 lines
  72. for (int i = 0; i < 10; i++) {
  73. String line = buffer.readLine();
  74. if (line != null) {
  75. System.out.println("Read: " + line);
  76. } else {
  77. System.out.println("End of stream");
  78. break;
  79. }
  80. }
  81. buffer.close();
  82. }
  83. }
  84. }

Add your comment