Get startedGet started for free

Stream chaining

Your company has data files in various text encodings. To standardize processing, your manager has asked you to implement a file reader that explicitly handles UTF-8 encoding. This requires chaining multiple streams together—a key concept in Java I/O.

The BufferedReader, InputStreamReader, FileInputStream, and StandardCharsets classes have been imported for you.

This exercise is part of the course

Importing Data in Java

View Course

Exercise instructions

  • Chain a BufferedReader to an InputStreamReader to a FileInputStream.
  • Read and print the first line from the file.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

public class StreamChainingExample {
    public static void main(String[] args) {
        String filePath = "sample_market_data.csv";
        
        // Chain three stream classes together
        try (
            BufferedReader reader = new ____(
                new ____(
                    new ____(filePath), 
                    StandardCharsets.UTF_8
                )
            )
        ) {
            // Read and print the first line
            String firstLine = reader.____();
            System.out.println("First line (UTF-8): " + ____);
            
            System.out.println("Successfully read using chained streams");
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}
Edit and Run Code