Line Filters in Logo

Our line filter program reads input from standard input, processes it, and then prints the result to standard output. In this case, it will write 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) {
        // Wrap System.in with a BufferedReader for efficient reading
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            String line;
            // Read each line from standard input
            while ((line = reader.readLine()) != null) {
                // Convert the line to uppercase
                String upperCaseLine = line.toUpperCase();
                // Print the uppercase line
                System.out.println(upperCaseLine);
            }
        } catch (IOException e) {
            // Print any errors to standard error
            System.err.println("Error: " + e.getMessage());
            System.exit(1);
        }
    }
}

This program uses BufferedReader to efficiently read input line by line. The readLine() method returns null when it reaches the end of the input, which is how we detect when to stop reading.

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

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

Then compile and use the line filter to get uppercase lines:

$ javac LineFilter.java
$ cat /tmp/lines | java LineFilter
HELLO
FILTER

This example demonstrates how to create a simple line filter in Java that reads from standard input and writes to standard output. You can modify the processing step (currently toUpperCase()) to create different types of line filters.