Print output of c++ .exe file in java - java

I want to run c++ .exe file from java and also want to print the output of .exe file.i tried and succeed to run c++ .exe file from java ,but i am not getting how can i print the output(in java output field) of c++ .exe file using java,i tried using processExitValue and waitfor methods but not getting desired output.The java code is here
int processExitVal = 0;
try {
Process p = Runtime.getRuntime().exec("cmd /c start rs.exe");
processExitVal = p.waitFor();
// p.getOutputStream();
//InputStreamReader ir=new InputStreamReader(p.getInputStream());
//BufferedReader t = new BufferedReader((new InputStreamReader(p.getInputStream())));
// int y=Integer.parseInt(t.readLine());
InputStream in=p.getInputStream();
System.out.println(in.read());
//System.out.println("output"+Process.getOutputStream());
} catch (IOException e) {
System.out.println("IOException");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("InterruptedException");
e.printStackTrace();
}
System.out.println(processExitVal);
System.out.println("Execution complete");
}
I will be thankful if u will help me out this problem. Thanks in advance

You could use a Scanner and then read lines from it. Are you sure your process is writing something on the standard output?
Edit:
read(): Reads the next byte of data from the input stream.
You have to use a Scanner:
Scanner scan = new Scanner(p.getInputStream());
String line = scan.getNextLine();
Regarding Deestan's answer: getInputStream() is the correct method here, we want the output of the process, that's an input for the application.

Use "rs.exe" instead of "cmd /c start rs.exe"
As example:
Process process = Runtime.getRuntime().exec("rs.exe");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while((line = in.readLine()) != null) {
System.out.println(line);
}

Related

How can I print the std output from Python script using Java runtime?

I want to print the std ouput of the following Python script using Java Runtime. My ideal result would simply print out "Hello World". Why am I getting java.io.IOException: Cannot run program "python": CreateProcess error=2, The system cannot find the file specified at java.lang.ProcessBuilder.start? My Path and Python environment variables are properly configured.
String commandline = "python /c start python C:\\Users\\Name\\HelloWorld.py"
try {
//TODO java.io.IOException: Cannot run program "dir"
Process process = Runtime.getRuntime().exec(commandline);
process.waitFor();
// Store command line output
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
if (result != null) {
PrintWriter out = resp.getWriter();
out.println("<div>" + result + "</div>");
System.exit(0);
} else {
PrintWriter out = null;
}
} catch (IOException e1) {
PrintWriter out = resp.getWriter();
e1.printStackTrace(out);
} catch (InterruptedException e2) {
PrintWriter out = resp.getWriter();
e2.printStackTrace(out);
}
One way to do this would be to change your python output to output to a file. I believe that you can do this somewhat simply by changing the process string to:
String commandline = "python /c start python C:\\Users\\Name\\HelloWorld.py > output.txt"
Then use any of the million ways that java has to open / read files to handle the file, which should contain the output from your python program. You may want to add a thread.sleep(1000) since your python script won't be running in the JVM and may need time to complete, since the instructions in your java program are synchronous.

Reading file passed in cmd

i have problem which is probably easy but in can't figure it out. I'm writing simple java program called task1 to read a file and calculate some values. I run this program in cmd like this:
cmd: java task1 calculate
Word "calculate" after "task1" is an argument which start my method to calculate some values. But i would like to calculate some values in a file called values.txt. My problem is that i don't know how to write my code to that read file. This file is passed as argument in cmd like that:
cmd: java task1 calculate < values.txt
hope, you can understand my problem. It Would be awesome if you can just tell me how to print this values in my file
if(args.length == 0)
{
System.out.println("Insert some arguments");
}
else if(args[0].equals("calculate"))
{
//here i would like to read my file (values.txt)
}
I appreciate your help and i am sorry for my bad English.
You should use buffered reader for that.
When you do
cmd: java task1 calculate < values.txt
you pass the contents of values.txt in the program as standard input.
The code would look like this
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String line = bufferedReader.readLine();
This way you read a line with BufferedReader.
For more please consult http://alvinalexander.com/java/java-bufferedreader-readline-string-examples
PS: It is also possible to directly read a file from disk, no need to pipe it to the program.
You do that like this:
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));
You can try Files#readAllLines(). This will read a text file and store every line in
a List collection:
//Path valuesPath = Paths.get("VALUES_DIR", "values.txt");
Path valuesPath = Paths.get("./" + args[0]);
try {
List<String> lines = Files.readAllLines(valuesPath, Charset.defaultCharset()));
for (String line : lines) { //print lines (or do whatever you need)
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Where args[0] is the name of the file to read (on the same directory where the task1.jar is).
Call your java program as:
java -jar task1.jar values.txt
EDIT:
To read piped file as standard in:
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) { //print lines (or do whatever you need)
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
call your task as:
java task1 calculate < VALUES_PATH\values.txt
Where VALUES_PATH is the complete path where your file is.
Note that when you use < then you can't get back the command line in your own program.

Control a command line program session via Java

I have a computer algebra program (called Reduce) that works in the shell in an interactive manner: launch Reduce in the shell, then you can define variables, compute this and that, and what not. Reduce prints the output into the shell. My idea is that I want to build a frontend for this text-based program that evaluates its output and converts it into a nice LaTeX style formula. For this I want to use Java.
I can start Reduce via exec(). But how can I emulate text input to the opened shell, and how can I read back what Reduce writes into the shell?
Thanks
Jens
Edit 1: Current Code
// get the shell
Runtime rt = Runtime.getRuntime();
// execute reduce
String[] commands = {"D:/Programme/Reduce/reduce.com", "", ""};
Process proc = null;
try {
proc = rt.exec(commands);
} catch (Exception e) {
System.out.println("Error!\n");
}
// get the associated input / output / error streams
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedWriter stdOutput = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
try {
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
try {
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
}
You need to get the streams associated with the process including the InputStream, OutputStream, and ErrorStream. You then can send messages to the process via the OutputStream and then read info from the process via the InputStream and the ErrorStream.
From some code of mine:
final ProcessBuilder pBuilder = new ProcessBuilder(TEST_PROCESS_ARRAY);
final Process proc = pBuilder.start();
procInputStream = proc.getInputStream();
errorStream = proc.getErrorStream();
errorSBuffer = new StringBuffer();
streamGobblerSb = new StreamGobblerSb(errorStream, "Autoit Error", errorSBuffer);
new Thread(streamGobblerSb).start();
final Scanner scan = new Scanner(procInputStream);
You may want to look into using the Process class.
http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html
I believe you may be able to start the process, and then use getOutputStream() to feed commands into the process.
While this is not strictly an answer, I discovered that it is more convenient for me to stick with PHP's function proc_open(). That way I can include the output directly in the frontend and do not need to worry about the communication between my Java program and the html frontend.
For everybody who wants to stick to the Java method: the article http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html is a good reference.

capture output from c++ in java without returning

i'm working on java SWING to make GUI for c++ programming . i need the c++ program to be executed in a loop without returning to the java. During this loop i want to capture some output without stepping through
return 0; in c++ program
can i capture output from the c++ file without returning to the java GUI ??
this is my out and in process in my code
try {
int out = 0;
String line;
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;
// calling the exe file
Process process = new ProcessBuilder("unpattern.exe").start();
stdin = process.getOutputStream();
stderr = process.getErrorStream();
stdout = process.getInputStream();
// input process
// "write" the parms into stdin
line = "1";
stdin.write(line.getBytes());
stdin.flush();
//line = "tx.getText()" + "\n";
// stdin.write(line.getBytes());
// stdin.flush();
stdin.close();
// output process
// clean up if any output in stdout
BufferedReader brCleanUp =
new BufferedReader(new InputStreamReader(stdout));
while ((line = brCleanUp.readLine()) != null) {
// counter of the defects
System.out.println(line);
} catch (IOException ex) {
Logger.getLogger(QeyeGui3.class.getName()).log(Level.SEVERE, null, ex);
}
Your while loop is missing its closing brace:
// ....
while ((line = brCleanUp.readLine()) != null) {
// counter of the defects
System.out.println(line);
// **** it should go here
}
I suggest you continuously get the text that is passed into the BufferedReader in your while loop. If you are doing this within a Swing application's SwingWorker, then you could use the publish/process method pair to update the Swing GUI with the information that is transmitted.
i could to find a suitable solution for my problem in this link
Capture the output of DOS (command prompt) and display in a JAVA Frame
i added the buffer in string builder so i could make it :)
thank you for every help :)

Communicating with C++ process from Java

First, I saw a few Q's about this issue in the site, but didn't see any answer that solve my problem.
I have a program written in Java and it calls a cmd program written in C++. (this is an assumption since I don't have the actual source) I know the expected I/O of the C++ program, in the cmd it is two lines of output and then it waits for string input.
I know that the first output line of the program is through error stream, and I receive it properly (this is expected), but I don't get the second line in error or input stream.
I tried to write to the program right after the first line ( the error line) and didn't got stuck, but there was no response.
I tried using 3 different threads, for each stream, but again, nothing was received in input/error stream after the first line, and the program didn't respond to writing through output stream.
My initializers are:
Process p = Runtime.getRuntime().exec("c:\\my_prog.exe");
BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
Is it possible at all or maybe it depends on the C++ program?
Thanks,
Binyamin
If you want to call native applications like C and C++ from Java, you need to use JNI.
I would suggest to put the input in the program when it has started, it will propably use that as input when it wants it.
Here is how I execute any command line in Java. This command line may execute any program:
private String executionCommandLine(final String cmd) {
StringBuilder returnContent = new StringBuilder();
Process pr;
try {
Runtime rt = Runtime.getRuntime();
pr = rt.exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = null;
while ((line = input.readLine()) != null) {
returnContent.append(line);
}
input.close();
LOG.debug(returnContent.toString());
// return the exit code
pr.waitFor();
} catch (IOException e) {
LOG.error(e.getMessage());
returnContent = new StringBuilder();
} catch (InterruptedException e) {
LOG.error(e.getMessage());
returnContent = new StringBuilder();
}
return returnContent.toString();
}

Categories

Resources