1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| import java.io.PrintWriter;
import java.util.Scanner;
public class TestIO {
static interface Test {
void test() throws Exception;
}
public static void main(String... args) throws Exception {
Test test1 = new Test() {
@Override
public void test() throws Exception {
String command = "echo bonjour";
Process process = Runtime.getRuntime().exec(command);
Scanner scanner = new Scanner(process.getInputStream());
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
}
};
Test test2 = new Test() {
@Override
public void test() throws Exception {
String command = "for i in 'a b'; do echo $i; done";
Process process = Runtime.getRuntime().exec(command);
Scanner scanner = new Scanner(process.getInputStream());
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
}
};
Test test3 = new Test() {
@Override
public void test() throws Exception {
String command = "sh -c \"for i in 'a b'; do echo $i; done\"";
Process process = Runtime.getRuntime().exec(command);
Scanner scanner = new Scanner(process.getInputStream());
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
}
};
Test test4 = new Test() {
@Override
public void test() throws Exception {
String command = "sh";
Process process = Runtime.getRuntime().exec(command);
PrintWriter writer = new PrintWriter(process.getOutputStream());
writer.println("for i in 'a b'; do echo $i; done");
Scanner scanner = new Scanner(process.getInputStream());
System.out.println("before hasNextLine()");
while (scanner.hasNextLine()) {
System.out.println("after hasNextLine()");
String line = scanner.nextLine();
System.out.println(line);
}
}
};
Test[] tests = { test1, test2, test3, test4 };
for (int i = 0; i < tests.length; i++) {
try {
System.out.println("==== DEBUT TEST " + i + " ====");
tests[i].test();
} catch (Exception e) {
System.err.println("test " + i + " failed");
e.printStackTrace();
} finally {
System.out.println("==== FIN TEST " + i + " ====");
Thread.sleep(1000);
}
}
}
} |