Title here
Summary here
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:
BufferedReader
to read input lines efficiently.readLine()
method is used to read each line of input.while
loop to process lines until we reach the end of input (when readLine()
returns null
).toUpperCase()
method is used to convert each line to uppercase.try-catch
block to handle potential IOException
s 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.