- Как с помощью Java выполнить Shell-команду
- Зависимость операционной системы
- Ввод и вывод
- Runtime.exec()
- ProcessBuilder
- Заключение
- How to Execute Cmd Commands via Java
- How to execute cmd commands through java
- How to execute cmd commands via Java
- How to execute cmd command in Java class?
- Running Command Line in Java
- Execute CMD command through JSP file
Как с помощью Java выполнить Shell-команду
В этом руководстве мы рассмотрим два способа выполнения shell -команд из программы на Java . Первый способ – использовать класс Runtime и вызвать его метод exec . Второй (более гибкий способ) – создать экземпляр класса ProcessBuilder .
Зависимость операционной системы
Сначала нужно определить операционную систему, на которой работает наша JVM . В Windows необходимо запустить команду в качестве аргумента оболочки cmd.exe, а в остальных ОС мы будем использовать стандартную оболочку sh:
boolean isWindows = System.getProperty("os.name") .toLowerCase().startsWith("windows");
Ввод и вывод
Также нужно подключиться к входным и выходным потокам нашего процесса. По крайней мере, нужно получить выходные данные, иначе процесс зависнет.
Реализуем класс StreamGobbler, который использует InputStream :
private static class StreamGobbler implements Runnable < private InputStream inputStream; private Consumerconsumer; public StreamGobbler(InputStream inputStream, Consumer consumer) < this.inputStream = inputStream; this.consumer = consumer; >@Override public void run() < new BufferedReader(new InputStreamReader(inputStream)).lines() .forEach(consumer); >>
Примечание. Этот класс реализует интерфейс Runnable , а это означает, что он может быть выполнен любым исполнителем.
Runtime.exec()
Метод Runtime.exec() — это простой, но недостаточно гибкий способ создания нового подпроцесса .
В следующем примере мы запросим список пользователей из локальной директории и выведем его в консоли:
String homeDirectory = System.getProperty("user.home"); Process process; if (isWindows) < process = Runtime.getRuntime() .exec(String.format("cmd.exe /c dir %s", homeDirectory)); >else < process = Runtime.getRuntime() .exec(String.format("sh -c ls %s", homeDirectory)); >StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), System.out::println); Executors.newSingleThreadExecutor().submit(streamGobbler); int exitCode = process.waitFor(); assert exitCode == 0;
ProcessBuilder
Класс ProcessBuilder является более гибким в использовании, чем Runtime. Он позволяет настраивать целый ряд параметров.
- изменить рабочий каталог, в котором работает shell-команда,
- перенаправить потоки ввода и вывода;
- наследовать их в потоках текущего процесса JVM, используя builder.inheritIO().
ProcessBuilder builder = new ProcessBuilder(); if (isWindows) < builder.command("cmd.exe", "/c", "dir"); >else < builder.command("sh", "-c", "ls"); >builder.directory(new File(System.getProperty("user.home"))); Process process = builder.start(); StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), System.out::println); Executors.newSingleThreadExecutor().submit(streamGobbler); int exitCode = process.waitFor(); assert exitCode == 0;
Заключение
Shell команды в Java можно выполнять двумя различными способами. Но если нужно настроить выполнение созданного процесса, то используйте класс ProcessBuilder .
Программные исходники примеров, приведенных в этой статье, доступны на GitHub .
How to Execute Cmd Commands via Java
One way to run a process from a different directory to the working directory of your Java program is to change directory and then run the process in the same command line. You can do this by getting cmd.exe to run a command line such as cd some_directory && some_program .
The following example changes to a different directory and runs dir from there. Admittedly, I could just dir that directory without needing to cd to it, but this is only an example:
import java.io.*;
public class CmdTest public static void main(String[] args) throws Exception ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) line = r.readLine();
if (line == null) < break; >
System.out.println(line);
>
>
>
Note also that I’m using a ProcessBuilder to run the command. Amongst other things, this allows me to redirect the process’s standard error into its standard output, by calling redirectErrorStream(true) . Doing so gives me only one stream to read from.
This gives me the following output on my machine:
C:\Users\Luke\StackOverflow>java CmdTest
Volume in drive C is Windows7
Volume Serial Number is D8F0-C934
Directory of C:\Program Files\Microsoft SQL Server
29/07/2011 11:03 .
29/07/2011 11:03 ..
21/01/2011 20:37 100
21/01/2011 20:35 80
21/01/2011 20:35 90
21/01/2011 20:39 MSSQL10_50.SQLEXPRESS
0 File(s) 0 bytes
6 Dir(s) 209,496,424,448 bytes free
How to execute cmd commands through java
Process process = Runtime.getRuntime().exec("cmd /c start cmd.exe /K java -jar selenium-server-standalone-2.44.0.jar -role hub");
However this will run executable jar from your current directory, where you .class file exist.
How to execute cmd commands via Java
The code you posted starts three different processes each with it’s own command. To open a command prompt and then run a command try the following (never tried it myself):
try // Execute command
String command = "cmd /c start cmd.exe";
Process child = Runtime.getRuntime().exec(command);
// Get output stream to write from it
OutputStream out = child.getOutputStream();
out.write("cd C:/ /r/n".getBytes());
out.flush();
out.write("dir /r/n".getBytes());
out.close();
> catch (IOException e) >
How to execute cmd command in Java class?
what’s the problem with this code. It’s perfectly working. opens and shows content of the file 111.txt
try String str ="C:/uploaded_files/111.txt";
Process process = Runtime.getRuntime().exec(new String[]);
System.out.println(str);
> catch (Exception ex) <>
please check whether the path is correct and whether the directories and files are not missed or spelled
Running Command Line in Java
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");
Execute CMD command through JSP file
Method exec (in class java.lang.Runtime ) does not serve as the equivalent of a command prompt window. The method arguments are the name of an executable that you wish to run – which in your case is schtasks – together with any options required by that command. Again, in your case the command options are:
/query /tn "\\dummy\\file" /v /fo list
However, as stated in the javadoc for class java.lang.Process
As of 1.5, ProcessBuilder.start() is the preferred way to create a Process .
Therefore you should rather use class java.lang.ProcessBuilder.
Also, since you are launching the command from Java code, you should use Java code to handle the output of the schtasks command.
The below code is a stand-alone, console application that demonstrates executing schtasks , locating the Last Run Time line from the command output and saving that line in a file.
Note that if file schtasks.exe is not in any of the folders of the System property java.library.path then you need to supply the full path to schtasks.exe .
(More notes after the code.)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
public class SchTasks
public static void main(String args[]) ProcessBuilder pb = new ProcessBuilder("schtasks.exe",
"/QUERY",
"/FO",
"LIST",
"/V",
"/TN",
"\\dummy\\file");
String result = null;
try Process p = pb.start(); // throws java.io.IOException
BufferedReader out = p.inputReader();
String output = out.readLine();
while (output != null) if (output.startsWith("Last Run Time:")) result = output;
>
output = out.readLine();
>
int status = p.waitFor(); // throws java.lang.InterruptedException
if (status == 0 && result != null) try (PrintWriter pw = new PrintWriter("C:\\Users\\me\\Desktop\\lastRunTime.txt")) pw.println(result);
>
>
>
catch (InterruptedException | IOException x) x.printStackTrace();
>
>
>
- Method inputReader was added to class Process in JDK 17 so if you are using an earlier version, you can use method getInputStream instead.
Here are the contents of file lastRunTime.txt after I ran the above code.
Last Run Time: 30/11/1999 00:00:00
I assume that you actually need to do something with the actual last run time (of task \\dummy\\file ) so rather than save it to a file, you can convert it to a timestamp in Java code. The below code replaces the part of the above code that saves the result to a file.
if (status == 0 && result != null) String[] parts = result.split(":\\s", 2);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss",
Locale.ENGLISH);
LocalDateTime lastRunTime = LocalDateTime.parse(parts[1], formatter);
System.out.println("Last Run Time: " + lastRunTime);
>
- javadoc for method split (in class java.lang.String )
- Regular Expressions lesson in Oracle’s Java tutorials.
- Date Time trail in Oracle’s Java tutorials.