Android java execute cmd

Executing Shell Commands with Java

Introduction

In this article, we’ll take a look at how we can leverage the Runtime and ProcessBuilder classes to execute shell commands and scripts with Java.

We use computers to automate many things in our daily jobs. System administrators run many commands all the time, some of which are very repetitive and require minimal changes in-between runs.

This process is also ripe for automation. There’s no need to run everything manually. Using Java, we can run single or multiple shell commands, execute shell scripts, run the terminal/command prompt, set working directories and manipulate environment variables through core classes.

Runtime.exec()

The Runtime class in Java is a high-level class, present in every single Java application. Through it, the application itself communicates with the environment it’s in.

By extracting the runtime associated with our application via the getRuntime() method, we can use the exec() method to execute commands directly or run .bat / .sh files.

The exec() method offers a few overloaded variations:

  • public Process exec(String command) — Executes the command contained in command in a separate process.
  • public Process exec(String command, String[] envp) — Executes the command , with an array of environment variables. They’re provided as an array of Strings, following the name=value format.
  • public Process exec(String command, String[] envp, File dir) — Executes the command , with the specified environment variables, from within the dir directory.
  • public Process exec(String cmdArray[]) — Executes a command in the form of an array of Strings.
  • public Process exec(String cmdArray[], String[] envp) — Executes a command with the specified environment variables.
  • public Process exec(String cmdarray[], String[] envp, File dir) — Executes a command, with the specified environment variables, from within the dir directory.

It’s worth noting that these processes are run externally from the interpreter and will be system-dependent.

What’s also worth noting is the difference between String command and String cmdArray[] . They achieve the same thing. A command is broken down into an array anyway, so using any of these two should yield the same results.

It’s up to you to decide whether exec(«dir /folder») or exec(new String[] <"dir", "/folder">is what you’d like to use.

Let’s write up a few examples to see how these overloaded methods differ from each other.

Executing a Command from String

Let’s start off with the simplest approach out of these three:

Running this code will execute the command we’ve supplied in String format. However, we don’t see anything when we run this.

To validate if this ran correctly, we’ll want to get ahold of the process object. Let’s use a BufferedReader to take a look at what’s going on:

Now, when we run this method after the exec() method, it should yield something along the lines of:

Keep in mind that we’ll have to extract the process information from the Process instances as we go through other examples.

Specify the Working Directory

If you’d like to run a command from, say, a certain folder, we’d do something along the lines of:

Here, we’ve provided the exec() method with a command , a null for new environment variables and a new File() which is set as our working directory.

The addition of cmd /c before a command such as dir is worth noting.

Since I’m working on Windows, this opens up the cmd and /c carries out the subsequent command. In this case, it’s dir .

The reason why this wasn’t mandatory for the ping example, but is mandatory for this example is nicely answered by an SO user.

Running the previous piece of code will result in:

Let’s take a look at how we could supply the previous command in several individual parts, instead of a single String:

Running this piece of code will also result in:

Ultimately, regardless of the approach — using a single String or a String array, the command you input will always be broken down into an array before getting processed by underlying logic.

Which one you’d like to use boils down just to which one you find more readable.

Using Environment Variables

Let’s take a look at how we can use environment variables:

We can supply as many environment variables as we’d like within the String array. Here, we’ve just printed the value of var1 using echo .

Running this code will return:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Running .bat and .sh Files

Sometimes, it’s just much easier to offload everything into a file and run that file instead of adding everything programmatically.

Читайте также:  How working android studio

Depending on your operating system, you’d use either .bat or .sh files. Let’s create one with the contents:

Then, let’s use the same approach as before:

This’ll open up the command prompt and run the .bat file in the working directory we’ve set.

Running this code surely enough results in:

With all of the overloaded exec() signatures taken care of, let’s take a look at the ProcessBuilder class and how we can execute commands using it.

ProcessBuilder

ProcessBuilder is the underlying mechanism that runs the commands when we use the Runtime.getRuntime().exec() method:

JavaDocs for the Runtime class

Taking a look at how the ProcessBuilder takes our input from the exec() method and runs the command, gives us a good idea of how to use it as well.

It accepts a String[] cmdarray , and that’s enough to get it running. Alternatively, we can supply it with optional arguments such as the String[] envp and File dir .

Let’s explore these options.

ProcessBuilder: Executing Command from Strings

Instead of being able to provide a single String, such as cmd /c dir , we’ll have to break it up in this case. For example, if we wanted to list the files in the C:/Users directory like before, we’d do:

To actually execute a Process , we run the start() command and assign the returned value to a Process instance.

Running this code will yield:

However, this approach isn’t any better than the previous one. What’s useful with the ProcessBuilder class is that it’s customizable. We can set things programmatically, not just via commands.

ProcessBuilder: Specify the Working Directory

Instead of supplying the working directory via the command, let’s set it programmatically:

Here, we’ve set the working directory to be the same as before, but we’ve moved that definition out of the command itself. Running this code will provide the same result as the last example.

ProcessBuilder: Environment Variables

Using ProcessBuilder s methods, it’s easy to retrieve a list of environment variables in the form of a Map . It’s also easy to set environment variables so that your program can use them.

Let’s get the environment variables currently available and then add some for later use:

Here, we’ve packed the returned environment variables into a Map and ran a forEach() on it to print out the values to our console.

Running this code will yield a list of the environment variables you have on your machine:

Now, let’s add an environment variable to that list and use it:

Running this code will yield:

Of course, once the program has finished running, this variable will not stay in the list.

ProcessBuilder: Running .bat and .sh Files

If you’d like to run a file, again, we’d just supply the ProcessBuilder instance with the required information:

Running this code results in the command prompt opening up and executing the .bat file:

Conclusion

In this article, we’ve explored examples of running shell commands in Java. We’ve used the Runtime and ProcessBuilder classes to do this.

Using Java, we can run single or multiple shell commands, execute shell scripts, run the terminal/command prompt, set working directories and manipulate environment variables through core classes.

Источник

How to Execute Operating System Commands in Java

Although Java is a cross-platform programming language, sometimes we need to access to something in an operating system dependent way. In other words, we need a Java program to call native commands that are specific to a platform (Windows, Mac or Linux). For example, querying hardware information such as processer ID or hard disk ID requires invoking a kind of native command provided by the operating system. Throughout this tutorial, you will learn how to execute a native command from within a Java program, including sending inputs to and getting outputs from the command.

Basically, to execute a system command, pass the command string to the exec() method of the Runtime class. The exec() method returns a Process object that abstracts a separate process executing the command. From the Process object we can get outputs from and send inputs to the command. The following code snippet explains the principle:

Now, let’s walk through some real code examples.

The following code snippet runs the ping command on Windows and captures its output:

It gives the following output in the standard console:

1. Getting Standard Output

Then invoke the readLine() method of the reader to read the output line by line, sequentially:

2. Getting Error Output

So it’s recommended to capture both the standard output and error output to handle both normal and abnormal cases.

3. Sending Input

Check the system clock, it is updated immediately.

4. Waiting for the process to terminate

Note that the waitFor() method returns an integer value indicating whether the process terminates normally (value 0) or not. So it’s necessary to check this value.

5. Destroying the process and checking exit value

NOTE: Using the waitFor() and exitValue() method is exclusive, meaning that either one is used, not both.

6. Other exec() methods

exec(String[] cmdarray)

This method is useful to execute a command with several arguments, especially arguments contain spaces. For example, the following statements execute a Windows command to list content of the Program Files directory:

Читайте также:  Драйвера xerox workcentre для андроид

For other exec() methods, consult the relevant Javadoc which is listed below.

API References:

Other Java File IO Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Как выполнять команды cmd через Java

Я пытаюсь выполнить аргументы командной строки через Java. Например:

выше открывается командная строка, но не выполняется cd или dir . Есть идеи? Я запускаю Windows XP, JRE6.

(Я пересмотрел свой вопрос, чтобы быть более конкретным. Следующие ответы были полезны, но не отвечают на мой вопрос.)

9 ответов

код, который вы опубликовали, запускает три разных процесса каждый со своей собственной командой. Чтобы открыть командную строку, а затем запустить команду, попробуйте следующее (Никогда не пробовал сам):

Я нашел это в forums.oracle.com

позволяет повторно использовать процесс для выполнения нескольких команд в Windows:http://kr.forums.oracle.com/forums/thread.jspa?messageID=9250051

нужно что-то вроде

Если вы хотите запустить несколько команд в оболочке cmd, вы можете создать одну команду следующим образом:

каждое исполнение exec порождает новый процесс со своей собственной средой. Таким образом, ваш второй вызов никак не связан с первым. Это просто изменится своя рабочий каталог, а затем выход (т. е. это фактически no-op).

Если вы хотите составлять запросы, вам нужно будет сделать это в течение одного вызова exec . Bash позволяет указывать несколько команд в одной строке, если они разделены точками с запятой; Windows CMD может разрешить то же самое, и если нет, всегда есть пакетные сценарии.

как говорит Петр, если этот пример на самом деле чего вы пытаетесь достигнуть, вы можете выполнить такую же вещь очень более эффективно, эффектно и платформу-безопасно с следующим:

вы не используете «cd» для изменения каталога, из которого выполняются ваши команды. Вам нужен полный путь к исполняемому файлу, который вы хотите запустить.

кроме того, перечисление содержимого каталога проще сделать с помощью классов файлов/каталогов

каждый из вызовов exec создает процесс. Второй и третий вызовы не выполняются в том же процессе оболочки, который вы создаете в первом. Попробуйте поместить все команды в скрипт bat и запустить его за один вызов: rt.exec(«cmd myfile.bat»); или подобное

этой runtime.exec(..) возвращает Process класс, который должен использоваться после выполнения вместо того, чтобы вызывать другие команды Runtime класс

если вы посмотрите на процесс doc вы увидите, что вы можете использовать

на котором вы должны работать, отправляя последовательные команды и извлекая выходные данные..

запись в поток out из процесса-неправильное направление. «выход» в таком случае означает от процесса к вам. Попробуйте получить / записать во входной поток для процесса и прочитать из выходного потока, чтобы увидеть результаты.

поскольку я также столкнулся с той же проблемой и потому, что некоторые люди здесь прокомментировали, что решение не работает для них, вот ссылка на сообщение, где было найдено рабочее решение.

Также см. «обновление» в лучшем ответе для использования Cygwin terminal

Источник

How to execute shell command from Java

By mkyong | Last updated: January 3, 2019

Viewed: 844,117 (+928 pv/w)

In Java, we can use ProcessBuilder or Runtime.getRuntime().exec to execute external shell command :

1. ProcessBuilder

2. Runtime.getRuntime().exec()

3. PING example

An example to execute a ping command and print out its output.

4. HOST Example

Example to execute shell command host -t a google.com to get all the IP addresses that attached to google.com. Later, we use regular expression to grab all the IP addresses and display it.

P.S “host” command is available in *nix system only.

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

I used the same (similar) code for my ShellWrapper. When I use commands like echo it works fine, but when I use commands like cat it returns an empty String….

can you please share your code using LS EAT AND Cat please

processBuilder.command(“bash”, “-c”, “cat /home/mkyong/web.log”);

processBuilder.command(“bash”, “-c”, “cat /home/mkyong/web.log”);

works fine, but when I pipe a string to Java process, then the

processBuilder.command(“bash”, “-c”, “cat /dev/stdin”);

I am trying to convert avro to json file through java, But it is not working
String output = obj.executeCommand(“java -jar /Users/xyz/Desktop/1server/jboss-as-7.1.1.Final/standalone/deployments/Command.war/WEB-INF/lib/avro-tools-1.7.7.jar tojson /Users/xyz/Desktop/avro/4.avro > /Users/xyz/Desktop/avro/D8EC9CC2A3E049648AFD4309B29D2A0F/4.json”);
But this is not working through java file,

I ran same command through terminal, avro is converted to json

Can you help me to run “java -jar * ” command

Did you find the solution for this ?

As a good practice, I wouldn’t catch Exception e. Just mention the two that need to be dealt with (IOException, InterruptedException) .

Why commands with pattern don’t work? Example: uptime | sed “s/^.* up \+\(.\+\), \+3 user.*$/\1/”

I am not able to execute stat command while fetching date of the file in Java code

I want to connect to DB in unix using java application and i have requirement while trying to connect with go to some specific location and then run java connection code ?
Coudl you please help me on this ?

I am trying to run a python script but it gives me error even if works in the terminal i am running from terminal in the same directory with java what problem can be it says file not found but it works in terminal

Читайте также:  Удалить рекламу вайбер андроид

i want to write a java class which will be deployed on a server .java class has to perform
1.listing out docker containers and login to particular docker image.
2.after logging it has to execute two commands in docker image

can anyone please help

I try to run a bat file which contain a “pause” command, that lock the java thread.

I need to execute a custom unix command to run a process and it will take around 10sec for the process to run. How to do it.

The Process.waitFor() statement should instead be invoked after the BufferedReader finishes reading the input stream of the Process. This fixes an issue I am having here: the program stucks and never returns but the actual command in my Mac Terminal exits within a second.

Another tip is that it is better to use Process.waitFor(long, TimeUnit) to prevent that the Java program hangs.

I also find that I will need to have Process.waitFor() statement invoked BEFORE the BufferedReader reads the input stream of the Process if I have BufferedReader.ready() added.

As an additional remark, using Process.waitFor(long, TimeUnit) isn’t the complete solution. In my case, the command never returns and it does not print anything in Terminal.
In this case, the BufferedReader.readLine() causes the program to hang. It seems that adding an if condition to check BufferedReader.ready() before BufferedRader.readLine() can solve the issue.

I want to execute 2 commands in a sequence.
1. cd D://
2. java -jar -role hub

I tried below code but it tries to execute jar file first and then cd :

ProcessBuilder builder = new ProcessBuilder(“cmd”,”/c”,”start”,”cmd.exe”,”/K”, “java -jar -role hub && cd \”D:\\””);
builder.redirectErrorStream(true);
Process p = builder.start();

any suggestion for first cd should get execute and then .jar?

please read D://foldername and java -jar jarFile

Where do I download the shell package?

To your own machine. lol

let’s say we type ‘mysql’ in command prompt.

c:mysql
then the prompt changes to:
mysql>
now in this we type sql commands.
Can we achieve/automate this with java?

The article would be even better with a note on how to run a shell file sitting in the resources directory.
Thanks for the jump start anyway !

I really like your articles on Java. For this one i guess i could not do as mentioned. I googled and figured out that you need to first connect to the linux box from java and then you can execute shell commands. I could not make the Linux commands run from Java which is on Windows using this code.

Hi How can we add Timeout ?

If I want to check my java version on Mac, I used the “PING” example and replaced the command string with my value i.e. String command = “java -version”;
but the command does not get executed at all. Can you please let me know what am I missing?

Mkyong your tutorials are always straight to the point, bravo.

Hi I am trying to create a Terminal Emulator for Linux using Java… Can you help me by giving a direction..

Thanks in advance…

Access denied. Option -c requires administrative privileges. —-how to fix admin issue on windows 8.1

ok i got it had to read -n yea, thanks

Using array parameter is better, because…when some parameter has blank ( ex. “ABC DE” ) it will be treated as 2 parameters…

Array parameter is more safe… рџ™‚

Sorry…english is not my mother tongue…

The following code allows you to set a timer, restart the timer on keywords, and specify if you want it to be sent to your log or not. This prevents several problems I’ve run into while programming on the command line.

The method is complex, very complex, but it works well and avoids loops in favor of waiting for a synchronized notification whenever possible. It uses three threads. The main thread launches the application and waits. The reader thread processes whatever comes out of the application. The watchdog thread monitors for timeout and gets kicked by the reader thread to restart the timer whenever a keyword is detected.

public String timeoutValueCheckingShellCommand(final String[] cmd, final String[] restartTimerKeywords, final int timeout,final boolean logLevel2) <

StringBuilder sb = new StringBuilder();

ProcessBuilder p = new ProcessBuilder(cmd);

final Process process = p.start();

TimeoutLogger is a place to hold a common object for use through

the various threads. It is used for logging of data, locking the

main thread on the processRunning object, timeout status and

monitoring of if the thread is alive or not.

TimeoutLogger(boolean realtime,Process p)<

private final StringBuilder log = new StringBuilder();

AtomicBoolean timedOut = new AtomicBoolean(false);

AtomicBoolean isRunning = new AtomicBoolean(true);

final Object isRunningLock=new Object();

AtomicBoolean isLogging = new AtomicBoolean(true);

final Object isLoggingLock=new Object();

final Process processRunning;

final Timer watchDogTimer = new Timer(timeout, new ActionListener() <

public void actionPerformed(ActionEvent evt) <

Log.level4Debug(“Watchdog Triggered! Command timed out.”);

synchronized void log(char c)<

for (String check:restartTimerKeywords)<

if (logstring.endsWith(check) && isRunning.get())<

Log.level4Debug(“Timer Reset on keyword “+check);

synchronized String get()<

final TimeoutLogger tl = new TimeoutLogger(logLevel2,process);

/*if the watchDogtimer elapses, the timedOut boolean is set true

and the processRunning object is notified to release main process

/*notify the processRunning object when the thread is complete to

release the lock.

Thread processMonitor = new Thread(new Runnable() <

public void run() <

Log.level4Debug(“Process Monitor done.”);

> catch (InterruptedException ex) <

Logger.getLogger(Shell.class.getName()).log(Level.SEVERE, null, ex);

processMonitor.setName(“Monitoring Process Exit Status from ” + cmd[0]);

reads the output and restarts the timer if required.

Thread reader = new Thread(new Runnable() <

Источник

Оцените статью