Output and error streams on windows console - java

I'm looking for a solution to print the output and error streams on the windows console.
A java program starts a rcp application (.exe) thanks to a command line :
Runtime.getRuntime.exec("example.exe");
Example.exe writes something after being started...
Then I want the java program to get the output stream of example.exe.
My problem is that it doesn't work and if I put the 2 eclipse runtime options: -console and -consoleLog, the output stream is printed in another console so I can't get back the stream...
Any ideas?
Edit: Here is my code to get the outputStream and errorStream (it works for a simple java program but not for a rcp application)
final Process process = Runtime.getRuntime().exec("toto.exe");
new Thread() {
public void run() {
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = "";
try {
while((line = inputReader.readLine()) != null) {
inputText = inputText + line;
}
System.out.println(inputText);
while((line = errorReader.readLine()) != null) {
errorText = errorText + line;
}
System.out.println(errorText);
} finally {
errorReader.close();
inputReader.close();
}
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}.start();

Related

Running python with command line in java

The program is stuck at p2.waitFor() (I tested with printing strings before and after)
public void score() {
this.toXML();
try {
Process p = Runtime
.getRuntime()
.exec("python sumocfg_maker.py Carrefour.net.xml Detectors.det.xml edgedata.csv -ef");
p.waitFor();
Process p2 = Runtime.getRuntime().exec("python simulation.py");
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null)
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p2.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
and simulation.py is
import os
os.system('cmd /c "sumo -c Simulation.sumocfg --duration-log.statistics --log duration.txt)
The simulation.py runs fine on its own. When I put the command in simulation.py in java, I get the same problem.
The System.out.println(line); prints out "Success" and then nothing
I left out code from simulation.py that saves a file that the java reads right after the p2.wait(), and without the p2.wait() the file never changes.
You have
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
But you need
BufferedReader input = new BufferedReader(new InputStreamReader(p2.getInputStream()));
since p is already finished, the bufferedreader will wait but never receive anything.

Trying to run an exe file created from a cpp file in java

I'm trying to run an executable file created from a cpp program in java. If I double-click the exe file, it works just fine, but if I run the file using ProcessBuilder, it gets stuck for some reason, it prints most of the expected output and doesn't continue, also making the entire Java program not responding.
here's my code:
String filePath = FirstScreenController.getFile().getPath();
ProcessBuilder launcher = new ProcessBuilder("ClusteringProgram\\Release\\main.exe",filePath);
launcher.redirectErrorStream(true);
try {
/*File file = FirstScreenController.getFile();
Path newPath = Paths.get(System.getProperty("user.dir")+"\\ClusteringProgram").resolve("K12.fasta");//Moving the file to the
Files.copy(Paths.get(file.getPath()), newPath, StandardCopyOption.REPLACE_EXISTING);*/
System.out.println("Execution started");
p = launcher.start();
InputStream stderr = p.getInputStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
p.waitFor();//Waiting for the process to finish running
System.out.println("Execution completed");
} catch (IOException | InterruptedException e) {e.printStackTrace();}
Close your stream. That's what's causing you to hang. I write code like this quite a bit.
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close(); // You need this or p can hang
p.waitFor();
In addition, you called launcher.redirectStandardError(true); so you actually need all this to gather both stdout and stderr together: The whole rest of this answer is wrong. I don't know what is causing the deadlock. I'm leaving the large code fragment here in case it's some strange library bug and it turns out that the dual-thread reading technique is required to work around it.
final object lock = new object();
InputStream stdout = p.getInputStream();
InputStreamReader isr = new InputStreamReader(stdout);
BufferedReader br = new BufferedReader(isr);
final InputStream stderr = p.getErrorStream();
one = new Thread() {
public void run() {
InputStreamReader isr2 = new InputStreamReader(stderr);
BufferedReader br2 = new BufferedReader(isr2);
while ((line2 = br2.readLine()) != null) {
synchronized(lock) {
System.out.println(line2);
}
}
br2.close(); // you need this or p can hang
}
};
one.start();
while ((line = br.readLine()) != null) {
synchronized(lock) {
System.out.println(line);
}
}
br.close(); // You need this or p can hang
for (;;) {
try {
one.join();
break;
} catch (InterruptedException v) {
/* if there's something that might want the main thread's attention handle it here */
}
}
p.waitFor();

capture the logcat output during the android junit test execution

I was able to capture the logcat output using below java code in android.
public void WriteLogCatOutput() {
StringBuilder log;
log=new StringBuilder();
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
}
} catch (IOException e) {
}
I can keep reading the logs, just by removing the "-d" flag in code above and placing it in a thread.
But is that possible to read the logcat outputs just with TWO calls/one call to the above method, so that we can capture the logcat output from the start of my JUnitTest and towards the end of JUnit Test and get only the logcat output in between?

Runtime.getRuntime failed to get output same time but later

I'm currently making firefox addon development GUI tool using Java. However I am stuck when trying to get output of a .bat file.
When I run .bat file using java I can see the output, but there are 3 commands written in the bat file. When first command executes I can get the output simultaneously. But when it execute second command output not coming. And when .bat file exist I get all the output which didn't come simultaneously.
I'm getting output immediately when it execute:
call "C:\mozilla-build\addon-sdk-1.16\bin\activate.bat
But I'm not getting output simultaneously for following command:
call cfx run
But I know it's executing because firefox window pops up. I get all the output suddenly when I execute proc.destroy();
This is my bat file:
#echo off
call %1
cd C:\Users\Madhawa.se\Desktop\workingfox\beauty
call cfx run
pause
This is my Java code:
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
Runtime rt = Runtime.getRuntime();
String[] commands = {"C:\\Users\\Madhawa.se\\Desktop\\workingfox\\runner\\foxrun.bat", "C:\\mozilla-build\\addon-sdk-1.16\\bin\\activate.bat"};
proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
proc.waitFor();
System.out.println("success");
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
t.start();
How to get output immediately and why it acts differently for this command?
i was able to fix it using process builder instead of runtime.exec .and inheriteIo doesn't work .it blocks the realtime output
Thread t = new Thread(new Runnable() {
private String s;
#Override
public void run() {
try {
Component selectedComponent = jTabbedPane2.getSelectedComponent();
if (selectedComponent instanceof MyTextArea) {
String response = "";
System.out.println("yes");
MyTextArea temptextarea = (MyTextArea) selectedComponent;
String xpiPath = new File(temptextarea.getNameX()).getParentFile().getPath();
String[] commands = {"C:\\Users\\Madhawa.se\\Desktop\\workingfox\\runner\\foxrun.bat", "C:\\mozilla-build\\addon-sdk-1.16\\bin\\activate.bat
ProcessBuilder process = new ProcessBuilder(commands);
process.redirectErrorStream(true);
Process shell = process.start();
//shell.waitFor();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(shell.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(shell.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println("s:" + s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println("w:" + s);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}

Java Temporary Files, read and write

I have this piece of code
package Classes;
import java.io.*;
public class IpAdministrator {
public Boolean isActive(String ipAddress) {
boolean isActive = false;
String cmd;
String OS = System.getProperty("os.name");
System.out.println(OS);
String tmpfolder = System.getProperty("java.io.tmpdir");
System.out.println(tmpfolder);
//iptmp.deleteOnExit();
if (OS.equals("Linux")) {
cmd = "ping " + ipAddress + " -c 1";
} else {
cmd = "cmd /c ping " + ipAddress + " -n 1";
}
try {
String s = null;
Process p = Runtime.getRuntime().exec(cmd);
File iptmp = File.createTempFile("ipresult", ".txt", new File(tmpfolder));
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
s = s.toString();
BufferedWriter writer = new BufferedWriter(new FileWriter(iptmp));
writer.write(s);
}
} catch (Exception ex) {
System.out.println(ex.getMessage().toString());
}
return isActive;
}
}
I want to write the result from the command in the temporary file, I found something related in other questions in this site, and it seems to work fine, but when I run this, the file is created with some random numers (ie: ipresult540677216848957037.txt) and it's empty, I can't figure out why, I also read that it's something related to java 1.7, so that means that I can't fill the file with information, there something that I'm missing?
Every time you open a file for writing that way -- i.e., every time you execute this line:
BufferedWriter writer = new BufferedWriter(new FileWriter(iptmp));
the file is truncated to zero length. Furthermore, since you never explicitly call close() on the BufferedWriter, line you do write will never actually be flushed to the file. As a result, no data ever makes it to the disk.
To do this correctly, first, move the line above to before the loop, so it only executes once. Second, after the loop, include code like
if (writer != null)
writer.close();
Finally, note that your program is needlessly broken on Macs, which are neither Linux, nor do they use cmd.exe. Instead of the way you've written this, you test explicitly for Windows, and use the Windows command line if you find it; otherwise, assume something UNIX-like, and use the Linux version.
You need to close the writer
BufferedReader stdInput = new BufferedReader(new InputStreamReader(
p.getInputStream()));
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(iptmp));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
s = s.toString();
writer.write(s);
}
} finally {
if (writer != null) {
writer.close();
}
}
If you are using java 7
try (BufferedWriter writer = new BufferedWriter(new FileWriter(
iptmp));) {
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
s = s.toString();
writer.write(s);
}
}

Categories

Resources