How to Execute Cmd Commands via Java

Run cmd commands through 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 <DIR> .
29/07/2011 11:03 <DIR> ..
21/01/2011 20:37 <DIR> 100
21/01/2011 20:35 <DIR> 80
21/01/2011 20:35 <DIR> 90
21/01/2011 20:39 <DIR> MSSQL10_50.SQLEXPRESS
0 File(s) 0 bytes
6 Dir(s) 209,496,424,448 bytes free

How to execute cmd commands through java

You can try below code

 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[]{"cmd.exe", "/c",str});
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");

http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

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,}", 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);
}

Refer to the following:

  • 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.


Related Topics



Leave a reply



Submit