Skip to main content

On This Page

How to Reset InputStream and Read File Again

2 min read
Share

These articles are AI-generated summaries. Please check the original sources for full details.

How to Reset InputStream and Read File Again

Java InputStreams provide a unidirectional data flow, yet sometimes revisiting previously read data is necessary. The InputStream class offers mark() and reset() methods to enable this functionality, allowing developers to effectively “bookmark” and return to specific positions within a stream.

Traditional stream processing assumes a one-way flow, which is efficient but inflexible when rewinding is required. Without mark() and reset(), reprocessing data often necessitates reloading the entire file, incurring significant performance costs and resource overhead.

Key Insights

  • markSupported() – returns false for the base InputStream class, 2025
  • ByteArrayInputStream supports mark() and reset() natively, offering a simple way to revisit data in memory.
  • BufferedInputStream requires a meaningful read-ahead limit when calling mark() to function correctly.

Working Example

import java.io.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class InputStreamReset {

    private static final String fileName = "test.txt"; // Assuming a file named test.txt exists

    @Test
    void givenBufferedInputStream_whenMarkAndReset_thenReadMarkedPosition() throws IOException {
        final int readLimit = 500;
        final char EXPECTED_CHAR = 'w';
        FileInputStream fis = new FileInputStream(fileName);
        BufferedInputStream bis = new BufferedInputStream(fis);
        bis.read(); // A
        bis.read(); // l
        bis.read(); // l
        bis.read(); // space
        bis.mark(readLimit); // at w
        bis.read();
        bis.read();
        bis.reset();
        char test = (char) bis.read();
        assertEquals(EXPECTED_CHAR, test);
    }
}

Practical Applications

  • Protocol Parsing: A network service parsing a custom protocol can use mark()/reset() to rewind and re-examine headers if initial parsing reveals inconsistencies.
  • Pitfall: Exceeding the read-ahead limit specified in mark() invalidates the mark, leading to an IOException when reset() is called.

References:

Continue reading

Next article

I Built My Own Shader Language: Cast

Related Content