Execute java file with Runtime.getRuntime().exec() - java

This code will execute an external exe application.
private void clientDataActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
Runtime.getRuntime().exec("C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe");
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
What if I want to execute external java file? Is it possible? For example like this command:
Runtime.getRuntime().exec("cmd.exe /C start cd \"C:\Users\sg552\Desktop\ java testfile");
The code does not work from java and cmd prompt. How to solve this?

First, you command line looks wrong. A execution command is not like a batch file, it won't execute a series of commands, but will execute a single command.
From the looks of things, you are trying to change the working directory of the command to be executed. A simpler solution would be to use ProcessBuilder, which will allow you to specify the starting directory for the given command...
For example...
try {
ProcessBuilder pb = new ProcessBuilder("java.exe", "testfile");
pb.directory(new File("C:\Users\sg552\Desktop"));
pb.redirectError();
Process p = pb.start();
InputStreamConsumer consumer = new InputStreamConsumer(p.getInputStream());
consumer.start();
p.waitFor();
consumer.join();
} catch (IOException | InterruptedException ex) {
ex.printStackTrace();
}
//...
public class InputStreamConsumer extends Thread {
private InputStream is;
private IOException exp;
public InputStreamConsumer(InputStream is) {
this.is = is;
}
#Override
public void run() {
int in = -1;
try {
while ((in = is.read()) != -1) {
System.out.println((char)in);
}
} catch (IOException ex) {
ex.printStackTrace();
exp = ex;
}
}
public IOException getException() {
return exp;
}
}
ProcessBuilder also makes it easier to deal with commands that might contain spaces in them, without all the messing about with escaping the quotes...

Related

I am trying to make an interface from where we can with on button click execute .exe files to install a s/w

This is my main class, wherein run(), I am calling one another method install setup() which is for exe files.
public static void main(String[] args) {
launch(args);
}
public void startSetup() {
Runnable task=new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
installSetup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread=new Thread(task);
thread.start();
}
Here is my installsetup() method
public void installSetup() {
try {
Runtime.getRuntime().exec("cmd /c C:path\\setup.exe", null, new File("C:pathfolder\\01_Setupexe"));
//process.waitFor();
} catch (IOException e) {
e.printStackTrace();
}
};
I am calling it in my controller class like this:
public class Controller extends Thread {
#FXML
private ComboBox<?> dsetup;
public void generateRandom() {
if(dsetup.getValue()!=null) dsetupValue = dsetup.getValue().toString();
if(dsetupValue!=null)call.startSetup();
Before I was just calling the install files with the exec method but not with threads concept, the application was working fine, but it was executing all the.exe files at once and then my interface freezes. So now I am using threads concept and trying to implement one thread at a time. I don't understand if it is a wrong way or not, but I do not get any error in console.
Runtime.exec has been obsolete for many years. Use ProcessBuilder instead:
ProcessBuilder builder = new ProcessBuilder("C:\\path\\setup.exe");
builder.directory(new File("C:pathfolder\\01_Setupexe"));
builder.inheritIO();
builder.start();
The inheritIO() method will make the spawned process use the Java program’s stdin, stdout, and stderr, so it will not hang waiting for input or waiting for an available output buffer.
I doubt you need the new Thread or the sleep call, but I don’t know what files you’re calling or whether they depend on each other.
Sadly exec has some pitfalls. Most of the time using the process aproche (see Listing 4.3) saved me related to buffer issues and so on.
https://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html
import java.util.*;
import java.io.*;
public class MediocreExecJavac
{
public static void main(String args[])
{
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("javac");
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<ERROR>");
while ( (line = br.readLine()) != null)
System.out.println(line);
System.out.println("</ERROR>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}
Source: javaworld

open an application during runtime in Mac OSX using netbeans

I want to open an application during run time in Mac using netbeans i used the following code but it throws exception. I used this code for windows with few changes i used it in Mac. Can anyone pls suggest me the correct code.
else
{
try {
Runtime r = Runtime.getRuntime();
p = Runtime.getRuntime().exec("/Applications/TextEdit.app /Users/apple/Documents/java files/scratch files/hi.rtf");
A4 a4sObj = new A4(new String[]{jComboBox2.getSelectedItem().toString()});
} catch (IOException ex) {
Logger.getLogger(serialportselection.class.getName()).log(Level.SEVERE, null, ex);
}
}
Okay, so that took a little bit of digging. It seems the preferred way to run a .app bundle is to use the open command. In order to get the app to open a file, you have to use the -a parameter, for example...
import java.io.IOException;
import java.io.InputStream;
public class Test {
public static void main(String[] args) {
String cmd = "/Applications/TextEdit.app";
//String cmd = "/Applications/Sublime Text 2.app";
String fileToEdit = "/Users/.../Documents/Test.txt";
System.out.println("Cmd = " + cmd);
ProcessBuilder pb = new ProcessBuilder("open", "-a", cmd, fileToEdit);
pb.redirectErrorStream(true);
try {
Process p = pb.start();
Thread t = new Thread(new InputStreamConsumer(p.getInputStream()));
t.start();
int exitCode = p.waitFor();
t.join();
System.out.println("Exited with " + exitCode);
} catch (IOException | InterruptedException ex) {
ex.printStackTrace();
}
}
public static class InputStreamConsumer implements Runnable {
private InputStream is;
public InputStreamConsumer(InputStream is) {
this.is = is;
}
#Override
public void run() {
int read = -1;
try {
while ((read = is.read()) != -1) {
System.out.print((char)read);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

How to execute a bash script from java program

I would like my Java program to execute a bash script and return the output back to Java. The trick is my script starts some sort of 'interactive session' and I suppose that is why my Java application freezes (Enters an infinite loop I suppose). Here is the code I use to execute the script, I use ProcessBuilder in order to do that. I also tried
Runtime.getRuntime().exec(PathToScript);
It doesn't work either.
public class test1 {
public static void main(String a[]) throws InterruptedException, IOException {
List<String> commands = new ArrayList<String>();
List<String> commands1 = new ArrayList<String>();
commands.add("/Path/To/Script/skrypt3.sh");
commands.add("> /dev/ttys002");
ProcessBuilder pb = new ProcessBuilder(commands);
pb.redirectErrorStream(true);
try {
Process prs = pb.start();
Thread inThread = new Thread(new In(prs.getInputStream()));
inThread.start();
Thread.sleep(1000);
OutputStream writeTo = prs.getOutputStream();
writeTo.write("oops\n".getBytes());
writeTo.flush();
writeTo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class In implements Runnable {
private InputStream is;
public In(InputStream is) {
this.is = is;
}
#Override
public void run() {
try {
byte[] b = new byte[1024];
int size = 0;
while ((size = is.read(b)) != -1) {
System.out.println(new String(b));
}
is.close();
} catch (IOException ex) {
Logger.getLogger(In.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
And here is the script I try to execute. It works like a charm when I run it directly from terminal.
#!/bin/bash
drozer console connect << EOF > /dev/ttys002
permissions
run app.package.info -a com.mwr.example.sieve
exit
EOF
You should not be trying to add redirect instructions as part of the command name:
commands.add("/Path/To/Script/skrypt3.sh");
commands.add("> /dev/ttys002");
ProcessBuilder pb = new ProcessBuilder(commands);
Instead, use the redirectOutput method, something like this:
tty = new File("/dev/ttys002");
ProcessBuilder pb = new ProcessBuilder("/Path/To/Script/skrypt3.sh")
.redirectOutput(ProcessBuilder.Redirect.appendTo(tty))
.redirectError(ProcessBuilder.Redirect.appendTo(tty))
.start();
Though, it appears your bash script is already handling the redirection so not sure you need to do that in Java.
See this answer for more info.

getRuntime().exec() does nothing

I want a java program to execute the following shell command:
apktool.jar d /path/to/my/app.apk
This command perfectly works when executing it directly on command line.
Java Code:
public static void main(String[] args) {
String command = "apktool d /path/to/my/app.apk";
try {
Runtime.getRuntime().exec(command);
} catch (IOException e1) {
e1.printStackTrace();
}
}
There is no error, no exception. Nothing happens and i have the impression that I already searched the entire internet for a solution. Does anybody know what I am doing wrong? A simple command like
mkdir /path/to/a/new/folder
works without problems.
I tried the same using ProcessBuilder:
try {
Process process = new ProcessBuilder(command).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This time i only get "Cannot run program "apktool d /path/to/my/app.apk, No such file or directory". I can't even run the mkdir command.
You need to call the jar with java.exe, and you're not doing that. Also you need to trap the input and error streams from the process, something you can't do the way you're running this. Use ProcessBuilder instead, get your streams and then run the process.
For example (and I can only do a Windows example),
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class ProcessEg {
private static Process p;
public static void main(String[] args) {
String[] commands = {"cmd", "/c", "dir"};
ProcessBuilder pBuilder = new ProcessBuilder(commands);
pBuilder.redirectErrorStream();
try {
p = pBuilder.start();
InputStream in = p.getInputStream();
final Scanner scanner = new Scanner(in);
new Thread(new Runnable() {
public void run() {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
try {
int result = p.waitFor();
p.destroy();
System.out.println("exit result: " + result);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Try doing it like this:
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec("./path/apktool d /path/to/my/app.apk");
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
system.out.println(output.toString());
Creating first a process allows you to wait for a response and reads the output of the execution of your process.
If something is failing while running your shell command, you will have the error printed at the end.
Also, make sure your java program can access your shell script, or better provide the full path to it like:
./path/to/shell/apktool d /path/to/my/app.apk

How to run a mvn command from a java program?

I am building a Java program for automating a procedure in my server side. Normally I cd to Desktop/GIT/ and use this maven command "mvn integration-test -DskipTests -P interactive -e".
I am building a java program and I am trying to run that command line but so far I wasn't successful.
So far, here is the code:
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
Process theProcess = null;
try
{
theProcess = Runtime.getRuntime().exec("mvn integration-test -DskipTests -P interactive -e");
}
catch(IOException e)
{
System.err.println("Error on exec() method");
e.printStackTrace();
}
// read from the called program's standard output stream
try
{
inStream = new BufferedReader(new InputStreamReader( theProcess.getInputStream()));
System.out.println(inStream.readLine());
}
catch(IOException e)
{
System.err.println("Error on inStream.readLine()");
e.printStackTrace();
}
break;
}
}
in.close();
}
You should check out maven embedder; which is exactly the tool which you should use in case of embedding maven.
OK apparently maven embedder is not supported any more. Probably you can still get it working though, but I rather created a small sample for you which should work. Of course, replace the path for Maven:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Q {
public static void main(String[] args) throws IOException, InterruptedException {
Process p = null;
try {
p = Runtime.getRuntime().exec("C:/Applications/apache-maven-3.0.3/bin/mvn.bat integration-test -DskipTests -P interactive -e");
} catch (IOException e) {
System.err.println("Error on exec() method");
e.printStackTrace();
}
copy(p.getInputStream(), System.out);
p.waitFor();
}
static void copy(InputStream in, OutputStream out) throws IOException {
while (true) {
int c = in.read();
if (c == -1)
break;
out.write((char) c);
}
}
}
If you want to run it with other configuration options, try Jenkins as the continous integration tool. It is free and can be used with Tomcat.
I managed to run the mvn using the following code:
(I use this command: Runtime.getRuntime().exec(cmd);)
import java.io.*;
import java.util.ArrayList;
public class RunMvnFromJava {
static public String[] runCommand(String cmd)throws IOException
{
// The actual procedure for process execution:
//runCommand(String cmd);
// Create a list for storing output.
ArrayList list = new ArrayList();
// Execute a command and get its process handle
Process proc = Runtime.getRuntime().exec(cmd);
// Get the handle for the processes InputStream
InputStream istr = proc.getInputStream();
// Create a BufferedReader and specify it reads
// from an input stream.
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
String str; // Temporary String variable
// Read to Temp Variable, Check for null then
// add to (ArrayList)list
while ((str = br.readLine()) != null)
list.add(str);
// Wait for process to terminate and catch any Exceptions.
try {
proc.waitFor();
}
catch (InterruptedException e) {
System.err.println("Process was interrupted");
}
// Note: proc.exitValue() returns the exit value.
// (Use if required)
br.close(); // Done.
// Convert the list to a string and return
return (String[])list.toArray(new String[0]);
}
// Actual execution starts here
public static void main(String args[]) throws IOException
{
try
{
// Run and get the output.
String outlist[] = runCommand("mvn integration-test -DskipTests -P interactive -e");
// Print the output to screen character by character.
// Safe and not very inefficient.
for (int i = 0; i < outlist.length; i++)
System.out.println(outlist[i]);
}
catch (IOException e) {
System.err.println(e);
}
}
}
For windows, Try this
Process p=Runtime.getRuntime().exec("cmd.exe /c mvn install:install-file -Dfile=C:\\Users\\Desktop\\Desktop\\sqljdbc4-4.0.jar -Dpackaging=jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0");
For linux, **"cmd.exe /c"** is not needed.
try this:
List<String> commands=new ArrayList<>();
commands.add("mvn");
commands.add("-f");
commands.add();
commnads.add("integration-test");
commands.add("-DskipTests");
commands.add("-P");
commands.add("interactive");
commands.add("-e");
ProcessBuilder pb=new ProcessBuilder(commands);
pb.start();``

Categories

Resources