// standardio/Echo.java// How to read from standard inputimportjava.io.*;importonjava.TimedAbort;publicclassEcho{publicstaticvoidmain(String[]args){TimedAbort abort =newTimedAbort(2);newBufferedReader(new InputStreamReader(System.in)).lines().peek(ln ->abort.restart()).forEach(System.out::println); // Ctrl-Z or two seconds inactivity // terminates the program}}
// standardio/ChangeSystemOut.java
// Turn System.out into a PrintWriter
import java.io.*;
public class ChangeSystemOut {
public static void main(String[] args) {
PrintWriter out =
new PrintWriter(System.out, true);
out.println("Hello, world");
}
}
Hello, world
// standardio/Redirecting.java
// Demonstrates standard I/O redirection
import java.io.*;
public class Redirecting {
public static void main(String[] args) {
PrintStream console = System.out;
try (
BufferedInputStream in = new BufferedInputStream(
new FileInputStream("Redirecting.java"));
PrintStream out = new PrintStream(
new BufferedOutputStream(
new FileOutputStream("Redirecting.txt")))
) {
System.setIn(in);
System.setOut(out);
System.setErr(out);
new BufferedReader(
new InputStreamReader(System.in))
.lines()
.forEach(System.out::println);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
System.setOut(console);
}
}
}
// onjava/OSExecuteException.java
package onjava;
public class OSExecuteException extends RuntimeException {
public OSExecuteException(String why) {
super(why);
}
}
// onjava/OSExecute.java
// Run an operating system command
// and send the output to the console
package onjava;
import java.io.*;
public class OSExecute {
public static void command(String command) {
boolean err = false;
try {
Process process = new ProcessBuilder(
command.split(" ")).start();
try (
BufferedReader results = new BufferedReader(
new InputStreamReader(
process.getInputStream()));
BufferedReader errors = new BufferedReader(
new InputStreamReader(
process.getErrorStream()))
) {
results.lines()
.forEach(System.out::println);
err = errors.lines()
.peek(System.err::println)
.count() > 0;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
if (err)
throw new OSExecuteException(
"Errors executing " + command);
}
}
// standardio/OSExecuteDemo.java
// Demonstrates standard I/O redirection
// {javap -cp build/classes/main OSExecuteDemo}
import onjava.*;
public class OSExecuteDemo {}
Compiled from "OSExecuteDemo.java"
public class OSExecuteDemo {
public OSExecuteDemo();
}