I have written this program to execute cmd commands however the output from the cmd console isn't printed 'live' to my program's console (JTextArea). It's printed at the end of the call even though I append it every line.
What am I doing wrong here?
private String genCmd2;
JTextArea genCmdTextArea = new JTextArea();
genCmd2 = "ping google.com";
try {
//Execute a generated command
Process process = Runtime.getRuntime().exec(genCmd2);
//Print output to the program's console
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
output.append(line + "\n");
genCmdTextArea.append(output.toString());
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("-----------------------------------\nSuccess!");
} else {
System.out.println("exitVal != 0");
}
} catch (IOException e) {
System.out.println("IOException exception during process:");
e.printStackTrace();
genCmdTextArea.append("\n\n" + e.toString());
} catch (InterruptedException e) {
System.out.println("Interrupted exception during process:");
e.printStackTrace();
genCmdTextArea.append("\n\n" + e.toString());
}
Related
I am trying to run cmd commands using getRuntime().exec(). The problem is that it works only if my command string is ipconfig, whereas if I try to run commands like java -version or time, it then throws the error :
java.io.IOException: Cannot run program "time": CreateProcess error=2, The system cannot find the file specified
String command = "time";
Process p;
try {
p = Runtime.getRuntime().exec(command);
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
//System.out.println(line);
textField_1.setText(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I solved this issue by using ProcessBuilder. I still don't know why the earlier code didn't work for all the commands. But by using ProcessBuilder, I was able to perform any cmdquery.
Here's the code for reference:
String command_ping = "ping " + host_name;
try {
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", command_ping);
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuffer buffer = new StringBuffer();
String line = "";
while (true)
{
buffer.append(line).append("\n");
line = r.readLine();
if (line == null) { break; }
}
message_ping= buffer.toString();
p.waitFor();
r.close();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
I got a server applicatino in java in my computer and multiples virtual machines with Android OS. I would like execute the following command line in VM:
su am start -n <PackageName>/ <OtherAtribute>
Look what I already have:
The call:
cvb.accessShell(ip, 5555);
cvb.startApp(appPackageName, mainPath);
THe functions accessShell and startApp:
cvb.accessShell(ip, 5555);
cvb.startApp(appPackageName, mainPath);
public void accessShell(String ip, int port) {
String script = "/home/decom/1018119/adt-bundle-linux-x86_64-20131030/sdk/platform-tools/adb -s "
+ ip + ":" + port + " shell";
System.out.println(script);
try {
System.out.println("Get in");
Runtime.getRuntime().exec(script); // stuck here
System.out.println("Get out");
} catch (IOException e) {
System.out.println("Cant connect to shell");
}
}
public void startApp(String appPackageName, String mainPath) {
String script = "su am start -n " + appPackageName + "/" + mainPath;
System.out.println(script);
try {
Runtime.getRuntime().exec(script);
} catch (IOException e) {
System.out.println("Cant connect to shell");
}
}
The problem is (like the comments on code): My code stuck at shell access and when I run the exactly command by terminal, it works ok.
I tried read the output and nothing is printed.
Try this
Process p = Runtime.getRuntime().exec("ls -la");
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
so, in your code:
try {
System.out.println("Get in");
Process p = Runtime.getRuntime().exec(script);
System.out.println("Get out");
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Cant connect to shell");
}
I want to execute a program (System.getenv("appdata") + "ffmpeg"). I also want to be able get a process or something that could get me the consle output. I have tried "cmd /C " + System.getenv("appdata") + "ffmpeg" before and it didn't seem to work. Any help is appreciated!
Here is some code:
Process p = exec(testFFMpeg);
int ex = -1;
try {
ex = p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
CrashHandler.reportCrash("FFMpeg", "Unable to test FFMpeg", "start up with more permissions");
}
if(ex == 0){
System.out.println("Normal execution, exit value: " + ex);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
do{
try {
line = br.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
CrashHandler.reportCrash("FFMpeg", "Unable to test FFMpeg", "start up with more permissions");
}
}while(line != null);
}else{
System.out.println("Execution exit value: " + ex);
}
}
private static Process exec(String[] cmd){
try {
return Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
e.printStackTrace();
CrashHandler.reportCrash("FFMpeg", "Unable to test FFMpeg", "start up with more permissions");
}
The exact location of the file is: `System.getenv("appdata") + "\VinVid\" + "ffmpeg.exe".
I figured it out. The output was going to the error stream, not the inputStream.
You are missing path separator, try this
System.getenv("appdata") + "\\ffmpeg"
In your code change this line line = br.readLine(); to line += br.readLine();
This is how you run a windows process in java.
I don't know what output you want. If your asking to print the output of the process you ran, this code helps :
String line;
String pidInfo ="";
Process p =Runtime.getRuntime().exec(System.getenv("appdata") +"ffmpeg.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
pidInfo+=line;
}
input.close();
System.out.println(pidInfo);
I have a Junit / Silkuli test that runs on windows 7 and is dependent on an external program already running.
How can I check if the external program is running from inside the test?
You can run command "tasklist" from within java and look at the returned list to see if your program is in the list. something like:
String program = "eclipse.exe"; //or any other process
String listOfProcesses = getCommandOutput("tasklist");
if (listOfProcesses == null || listOfProcesses.isEmpty()) {
System.err.println("Unable to automatically determine if " + program + " is running");
} else {
if (listOfProcesses.contains(program)) {
System.out.println(program + " is running!");
} else {
System.out.println(program + " is not running!");
}
}//else: process list can be retrieved
and get the output from a command using a method such as:
public static String getCommandOutput(String command) {
String output = null; //the string to return
Process process = null;
BufferedReader reader = null;
InputStreamReader streamReader = null;
InputStream stream = null;
try {
process = Runtime.getRuntime().exec(command);
//Get stream of the console running the command
stream = process.getInputStream();
streamReader = new InputStreamReader(stream);
reader = new BufferedReader(streamReader);
String currentLine = null; //store current line of output from the cmd
StringBuilder commandOutput = new StringBuilder(); //build up the output from cmd
while ((currentLine = reader.readLine()) != null) {
commandOutput.append(currentLine + "\n");
}
int returnCode = process.waitFor();
if (returnCode == 0) {
output = commandOutput.toString();
}
} catch (IOException e) {
System.err.println("Cannot retrieve output of command");
System.err.println(e);
output = null;
} catch (InterruptedException e) {
System.err.println("Cannot retrieve output of command");
System.err.println(e);
} finally {
//Close all inputs / readers
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
System.err.println("Cannot close stream input! " + e);
}
}
if (streamReader != null) {
try {
streamReader.close();
} catch (IOException e) {
System.err.println("Cannot close stream input reader! " + e);
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.err.println("Cannot close reader! " + e);
}
}
}
//Return the output from the command - may be null if an error occured
return output;
}
I am working on an Editor application where I can compile and run c,cpp and Java file.I am developing this application using java programming language.I am developing it in Eclipse.
I am able to create new files(c,cpp and java) on specific locations and also I am able to save file to different-2 locations.
And for execution I am using following methods.
String compileFileCommand = "javac "+fileName;
Process compile_process = new ProcessBuilder(compileFileCommand).redirectErrorStream(true).start();
compile_process.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(compile_process.getInputStream()));
String line=reader.readLine();
while(line!=null) {
System.out.println(line);
line=reader.readLine();
}
My problem is that I am not able to compile files from their corresponding locations.
Always giving Exception
java.io.IOException: error=2, No such file or directory
Please tell me how can I compile and run all c,c++ & java files.
Please also give me any other suggestion for my application.
Edited ..
I have used these two methods for compiling and running.On Compiling it creates a class file in case of Java.But all the time I am getting null from InputStreams(both getErrorStream() and getInputStream()).
void compileJavaFile(String fileName)
{
String compileFileCommand = "javac " + fileName;
try
{
System.out.println("Executing Java File");
Process compileProcess = Runtime.getRuntime().exec(compileFileCommand);
String line = "";
BufferedReader bri = new BufferedReader(new InputStreamReader(compileProcess.getInputStream()));
BufferedReader bre = new BufferedReader(new InputStreamReader(compileProcess.getErrorStream()));
while ((line = bri.readLine()) != null)
{
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null)
{
System.out.println(line);
}
bre.close();
compileProcess.waitFor();
System.out.println("Done.");
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void runJavaFile(String fileName)
{
String runFileCommand = "java " + fileName.split(".java")[0];
try
{
System.out.println("runFileCommand : " + runFileCommand);
System.out.println("Running Java File");
Process runProcess = Runtime.getRuntime().exec(runFileCommand);
BufferedReader reader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
String line = reader.readLine();
System.out.println("line = " + line);
while (line != null)
{
System.out.println(line);
line = reader.readLine();
}
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
And for C and C++ I am using.
void compileCFile(String fileName)
{
String compileFileCommand = "gcc " + fileName;
resultString = "";
try
{
System.out.println("Compiling C File");
Process processCompile = Runtime.getRuntime().exec(compileFileCommand);
BufferedReader brCompileError = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String errorCompile = brCompileError.readLine();
if (errorCompile != null)
System.out.println("Error Compiler = " + errorCompile);
resultString += errorCompile +"\n";
BufferedReader brCompileRun = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String outputCompile = brCompileRun.readLine();
if (outputCompile != null)
System.out.println("Output Compiler = " + outputCompile);
resultString += outputCompile +"\n";
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void runCFile(String fileName)
{
String runFileCommand = "./" + fileName.split(".c")[0];
try
{
System.out.println("Running C File");
Process processRun = Runtime.getRuntime().exec(runFileCommand);
BufferedReader brRun = new BufferedReader(new InputStreamReader(processRun.getErrorStream()));
String errorRun = brRun.readLine();
if (errorRun != null)
System.out.println("Error Run = " + errorRun);
BufferedReader brResult = new BufferedReader(new InputStreamReader(processRun.getInputStream()));
String outputRun = brResult.readLine();
if (outputRun != null)
System.out.println("Output Run = " + outputRun);
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void compileCPPFile(String fileName)
{
String compileFileCommand = "g++ " + fileName;
try
{
System.out.println("Compiling CPP File");
Process processCompile = Runtime.getRuntime().exec(compileFileCommand);
BufferedReader brCompileError = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String errorCompile = brCompileError.readLine();
if (errorCompile != null)
System.out.println("Error Compiler = " + errorCompile);
resultString += errorCompile +"\n";
BufferedReader brCompileRun = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String outputCompile = brCompileRun.readLine();
if (outputCompile != null)
System.out.println("Output Compiler = " + outputCompile);
resultString += outputCompile +"\n";
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void runCPPFile(String fileName)
{
String runFileCommand = "./" + fileName.split(".cpp")[0];
try
{
System.out.println("Running CPP File");
Process processRun = Runtime.getRuntime().exec(runFileCommand);
BufferedReader brRun = new BufferedReader(new InputStreamReader(processRun.getErrorStream()));
String errorRun = brRun.readLine();
if (errorRun != null)
System.out.println("Error Run = " + errorRun);
BufferedReader brResult = new BufferedReader(new InputStreamReader(processRun.getInputStream()));
String outputRun = brResult.readLine();
if (outputRun != null)
System.out.println("Output Run = " + outputRun);
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
In case of C and C++ it show error like
g++: /media/disk/eclipse/\/UniversalIDE/CPP/firstCPP: No such file or directory
Please give me solution for my problems ..
Please try following,
Process p = Runtime.getRuntime().exec(command);
command is a string you pass. in command you can pass "javac Test.java" to compile your java file & just like that you can use other commands.
replace the line
String runFileCommand = "./" + fileName.split(".c")[0];
with
String runFileCommand = "./a.out";