When we run dd
without any options, it's default behavior is to take input from standard input and upon encountering the EOF (control + D)
it again pushes everything that was entered to standard output.
Kind of like this
[ec2-user@ip ~]$ dd
This is line 1
This is line 2
This is line 1
This is line 2
0+2 records in
0+1 records out
30 bytes (30 B) copied, 9.7963 s, 0.0 kB/s
[ec2-user@ip ~]$
I am trying to simulate the same thing in java code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
Process p = Runtime.getRuntime().exec("dd ");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String str = br.readLine();
while (str != null) {
System.out.println(str);
str = br.readLine();
}
}
}
so far I am able to write things into the standard input but I don't know how to send EOF (I have seen posts on how to send EOF from java but nothing seem to work here).
Also , I don't know how get the output from dd
to the standard output (i.e. using java) .
To write to the standard input stream of a subprocess, you use the stream from Process.getOutputStream
, since from your program's perspective it's an output stream. To send EOF, you close it.
For example:
Process p = Runtime.getRuntime().exec("dd ");
PrintStream print = new PrintStream(p.getOutputStream());
print.println("This is line 1");
print.println("This is line 2");
print.close(); // send EOF
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String str = br.readLine();
while (str != null) {
System.out.println(str);
str = br.readLine();
}
how get the output from dd to the standard output
You're already doing that: the stream you get from Process.getInputStream
is attached to the standard output stream of the subprocess (again, it's an "input" stream from your program's perspective), so you read from it and copy what you read into System.out.