Line Filters in Squirrel

Our line filter program reads input from stdin, processes it, and then prints a derived result to stdout. In this case, it writes a capitalized version of all input text. You can use this pattern to write your own Java line filters.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class LineFilter {
    public static void main(String[] args) {
        // Wrapping System.in with a BufferedReader gives us a convenient
        // readLine method that reads the next line of input.
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        String line;
        try {
            // Read lines until end of input
            while ((line = reader.readLine()) != null) {
                // Convert the line to uppercase
                String ucl = line.toUpperCase();

                // Write out the uppercased line
                System.out.println(ucl);
            }
        } catch (IOException e) {
            // Check for errors during reading
            System.err.println("Error: " + e.getMessage());
            System.exit(1);
        }
    }
}

To try out our line filter, first make a file with a few lowercase lines.

$ echo 'hello'   > /tmp/lines
$ echo 'filter' >> /tmp/lines

Then use the line filter to get uppercase lines.

$ cat /tmp/lines | java LineFilter
HELLO
FILTER

In this Java version:

  1. We use BufferedReader to read input lines efficiently.
  2. The readLine() method is used to read each line of input.
  3. We use a while loop to process lines until we reach the end of input (when readLine() returns null).
  4. The toUpperCase() method is used to convert each line to uppercase.
  5. We use a try-catch block to handle potential IOExceptions that might occur during reading.

This pattern can be adapted to create various types of line filters in Java, processing input line by line and producing modified output.