I got a code which is running and displaying output successfully if I am executing something like "dir" but not displaying the output if I am running "java -version" or other command from java. Please help:
public static void execJob(){
try{
ProcessBuilder pb = new ProcessBuilder("C:\\myPrograms\\jdk1.7.0_79\\bin\\java.exe", "-version");
pb.directory(new File("src"));
Process process = pb.start();
IOThreadHandler outputHandler = new IOThreadHandler(process.getInputStream());
outputHandler.start();
process.waitFor();
System.out.println(outputHandler.getOutput());
}catch(Exception e) {
System.out.println(e.toString());
}
}
private static class IOThreadHandler extends Thread {
private InputStream inputStream;
private StringBuilder output = new StringBuilder();
IOThreadHandler(InputStream inputStream) {
this.inputStream = inputStream;
}
public void run() {
Scanner br = null;
try {
br = new Scanner(new InputStreamReader(inputStream));
String line = null;
while (br.hasNextLine()) {
line = br.nextLine();
output.append(line + System.getProperty("line.separator"));
}
} finally {
br.close();
}
}
java -version writes to stderr, so you need pb.redirectErrorStream(true); to capture the output.
ProcessBuilder pb = new ProcessBuilder("C:\\myPrograms\\jdk1.7.0_79\\bin\\java.exe", "-version");
pb.redirectErrorStream(true);
...
private static class IOThreadHandler extends Thread {
private InputStream inputStream;
private StringBuilder output = new StringBuilder();
IOThreadHandler(InputStream inputStream) {
this.inputStream = inputStream;
}
public void run() {
try (Scanner br = new Scanner(new InputStreamReader(inputStream))) {
String line = null;
while (br.hasNextLine()) {
line = br.nextLine();
output.append(line).append(System.getProperty("line.separator"));
}
}
}
public String getOutput() {
return output.toString();
}
}
Related
I am trying to read a file and then take the contents of that file and have it executed as user input. I am using Scanner for reading files and user input but I am not sure if this is the correct way to go about this since Scanner for input can only System.in and so I am not sure how to pass data from file into input scanner for it to execute in the console. This is my code below for reading class
public class readingFile {
Scanner fileReading = new Scanner(new File("somecontent.txt"));
Scanner input = new Scanner(System.in);
public readingFile() throws FileNotFoundException {
}
public void startReading()
{
System.out.println("reading file...");
while(fileReading.hasNextLine()){
String data = fileReading.nextLine();
System.out.println(data);
Scanner input = new Scanner(System.in);
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class readingFile {
static String javaFileFullPath = "D://myfolder/Program.java";
public static void main(String[] args) {
executeJavaFile();
}
public static void executeJavaFile() {
try {
System.out.println("executing java program from file....");
Process compileProcess = Runtime.getRuntime().exec("cmd /c javac "+javaFileFullPath);
Thread.sleep(5000);
System.out.println(compileProcess.exitValue());
BufferedReader inputReader = new BufferedReader(new InputStreamReader(compileProcess.getInputStream()));
String line = "";
while ((line = inputReader.readLine()) != null) {
System.out.println(line);
}
inputReader.close();
Process runProcess = Runtime.getRuntime().exec("cmd /c java "+javaFileFullPath);
Thread.sleep(5000);
System.out.println(runProcess.exitValue());
BufferedReader inReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
String lineStr = "";
while ((lineStr = inReader.readLine()) != null) {
System.out.println(lineStr);
}
inReader.close();
} catch (Exception ex) {
System.out.println("Exception:"+ex.getMessage());
}
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class readingFile {
static String javaFileFullPath = "D://myfolder/Program.java";
public static void main(String[] args) {
executeJavaFile();
}
public static void executeJavaFile() {
try {
System.out.println("executing java program from file....");
Process compileProcess = Runtime.getRuntime().exec("cmd /c javac "+javaFileFullPath);
Thread.sleep(5000);
System.out.println(compileProcess.exitValue());
BufferedReader inputReader = new BufferedReader(new InputStreamReader(compileProcess.getInputStream()));
String line = "";
while ((line = inputReader.readLine()) != null) {
System.out.println(line);
}
inputReader.close();
Process runProcess = Runtime.getRuntime().exec("cmd /c java "+javaFileFullPath);
Thread.sleep(5000);
System.out.println(runProcess.exitValue());
BufferedReader inReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
String lineStr = "";
while ((lineStr = inReader.readLine()) != null) {
System.out.println(lineStr);
}
inReader.close();
} catch (Exception ex) {
System.out.println("Exception:"+ex.getMessage());
}
}
}
I'm trying to run shell script by using ProcessBuilder. The script works but it can't run after the java code. And error stream doesn't output message. I'm running it on centOS 6.9 computer. Please find below my code.
public static ArrayList<String> runCommand(ArrayList<String> command)throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(command);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
ArrayList<String> commandOutput = new ArrayList<>();
String str;
while((str = reader.readLine()) != null) {
commandOutput.add(str);
}
StringBuilder errorBuilder = new StringBuilder();
while((str = errorReader.readLine()) != null) {
errorBuilder.append(str);
}
String errorMessage = errorBuilder.toString();
if(!errorMessage.equals("")) {
String message = LOG_TAG + ",[runCommand] error:" + errorMessage;
System.out.println(message);
}
reader.close();
errorReader.close();
process.destroy();
return commandOutput;
}
In your case, you are reading something from the output stream of the process, till you consume everything. Then, you try to read error stream.
If the process writes some considerable number of characters on the error stream, the other process will block till they are consumed. To consume both error stream and output stream at the same time, you need to use threads.
You may follow the StreamGobbler technique. You may get some details from that page: https://www.javaworld.com/article/2071275/when-runtime-exec---won-t.html?page=2
This is some code influenced from the page:
public class StreamGobbler extends Thread {
private static final String EOL = System.lineSeparator();
private final InputStream inputStream;
private final StringBuilder output = new StringBuilder();
public StreamGobbler(InputStream inputStream) {
this.inputStream = inputStream;
}
public void run() {
try (InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line);
output.append(EOL);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public String getOutput() {
return output.toString();
}
}
In your code, you use StreamGobbler like this:
StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream());
StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream());
process.waitFor();
String commandOutput = outputGobbler.getOutput();
String errorMessage = errorGobbler.getOutput();
process.destroy();
Using an self-edited StreamGobbler to run a php script,
I am trying to input commands into the script while it is running...
StreamGobbler.java
private class StreamGobbler extends Thread {
InputStream is;
OutputStream os;
String line;
PMRunnerPro main;
public StreamGobbler(InputStream is, OutputStream os, PMRunnerPro main) {
this.is = is;
this.os = os;
this.main = main;
}
#Override
public void run() {
try {
BufferedReader reader = new BufferedReader (new InputStreamReader(is));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
line = reader.readLine();
while (line != null && ! line.trim().equals("--EOF--")) {
if (main.sSendNeeded) {
System.out.println("Sent");
writer.write(main.sCommand + "\n");
main.sSendNeeded = false;
main.sCommand = "";
}
main.outputBox.setText(main.outputBox.getText() + (line + "\n"));
line = reader.readLine();
}
writer.flush();
} catch(IOException ex) {
main.sRunning = false;
}
System.out.println("Over");
main.sRunning = false;
}
}
The command is sent to the script only when there is an output from the script.
I want the Thread to continuously check if there is any command to send to the script and then do so if there is any.
If I understood your intentions correctly...
Since you using blocking I/O, you need two threads for what you want:
1st thread will read script output, as you do now. Once output available, it will be shown in textarea;
2nd thread will read input from queue and forward it to script.
Here's code draft (notice that you may want to add synchronization between input and output workers, so input worker won't be able to send new command to script until previous command produces output from script, but that's up to you):
class InputWorker implements Runnable {
#Override
public void run() {
try {
BufferedReader reader = new BufferedReader (new InputStreamReader(is));
String line = reader.readLine();
while (line != null && ! line.trim().equals("--EOF--")) {
// show script output
}
} catch(IOException ex) {
//
}
}
}
class OutputWorker implements Runnable {
final BlockingQueue<String> commandQueue = new ArrayBlockingQueue<String>();
public void sendCommand(String command) {
commandQueue.add(command);
}
#Override
public void run() {
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
while (true) {
String command = commandQueue.take();
if ("EXIT".equals(command)) { return; }
writer.write(command);
writer.flush();
}
} catch(IOException ex) {
//
} catch (InterruptedException e) {
//
}
}
}
How can i get the stderr of a python binary? It is showing the output of the python script but it is not showing the errors that might be in the script, what java method should i be using? or is there a python command line argument that i can use to display the errors?
private String exec(String command)
{
try
{
String s = getApplicationInfo().dataDir;
File file2 = new File(s+"/py");
file2.setExecutable(true);
File externalStorage = Environment.getExternalStorageDirectory();
String strUri = externalStorage.getAbsolutePath();
PrintWriter out = new PrintWriter(strUri+"/temp.py");
out.write(command);
out.close();
saveRawToFile();
Process process = Runtime.getRuntime().exec(s+"/py "+strUri+"/temp.py");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0)
{
output.append(buffer, 0, read);
}
reader.close(); process.waitFor();
return output.toString();
}
catch (IOException e)
{ throw new RuntimeException(e); }
catch (InterruptedException e)
{ throw new RuntimeException(e); }
}
private void output(final String str)
{
Runnable proc = new Runnable() {
public void run()
{
outputView.setText(str);
outputView.setTextIsSelectable(true);
}
};
handler.post(proc);
}
Use Process#getErrorStream(), just like you used getOutputStream().
I'm running a Java program from another Java application using Runtime.getRuntime().exec like this
Process p1 = Runtime.getRuntime().exec("javac test.java");
Process p2 = Runtime.getRuntime().exec("java test");
The content of the test.java
import java.io.*;
class test
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(s);
}
}
I want to handle Input, Output and Error stream of the process p2.
I did capture of the output of the test.java, however, I do not know how to handle output and error.
Here is my code:
try {
String s = "";
InputStream istr = p2.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p2.getErrorStream()));
while ((s = br.readLine()) != null) {
System.out.println(s);
}
br.close();
while ((s = bre.readLine()) != null) {
System.out.println(s);
}
bre.close();
p2.waitFor();
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception err) {
err.printStackTrace();
}
The code above works fine for capturing the output of the test.java. But it does not display error of the test.java.
Could you please give me a sample code for fixing this problem and handling output stream or share idea? Thanks in advance
The solution I've always used is to create a separate thread to read one of the streams
So, in your case it should be something like
String s = "";
InputStream istr = p2.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p2.getErrorStream()));
new Thread(new Runnable() {
#Override
public void run() {
while ((s = br.readLine()) != null) {
System.out.println(s);
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
while ((s = bre.readLine()) != null) {
System.out.println(s);
}
}
}).start();
// when you are finished close streams