Run MS-DOS command from java program - java

How can i run MS-DOS command within my java program ?

How to run command-line or execute external application from Java:
import java.io.*;
public class Main {
public static void main(String args[]) {
try {
Runtime rt = Runtime.getRuntime();
//Process pr = rt.exec("cmd /c dir");
Process pr = rt.exec("c:\\helloworld.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}
}

Process p = Runtime.getRuntime().exec("cmd /C dir");
BufferedReader stdin = new BufferedReader(new InputStreamReader(p.getInputStream()));

Use a ProcessBuilder eg.
Process p = new ProcessBuilder("myCommand", "myArg").start();
This is the Java5 addition that has superseded Runtime.getRuntime().exec()

use Runtime.getRuntime().exec()

Related

Unable to run apktool command on shell from Java

I am trying to use the apktool from a Java program. I'm using this for creating a web service. However this command does not run on the shell from the Java program.
String cmd = "apktool d /home/ridhima/Test.apk" ;
try {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while((line = reader.readLine()) != null)
{
System.out.print(line + "\n");
}
p.waitFor();
}
catch (IOException | InterruptedException e1) {
e1.printStackTrace();
}
The command works perfectly fine directly from the shell.
Thanks but it works fine now. Since apktool is a wrapper script, it is probably not being recognized through the java program. Extracting the apktool.jar directly works.
try {
ProcessBuilder pb = new ProcessBuilder("/home/ridhima/java/jdk1.8.0/bin/java", "-jar", "apktool.jar","d","test.apk");
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
p.waitFor();
}catch (IOException | InterruptedException e1) {
e1.printStackTrace();
}
You maybe should wait for the process to complete
String cmd = "apktool d /home/ridhima/Test.apk" ;
try {
Process p = Runtime.getRuntime().exec(cmd);
// You maybe should wait for the process to complete
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while((line = reader.readLine()) != null)
{
System.out.print(line + "\n");
}
}
catch (IOException | InterruptedException e1) {
e1.printStackTrace();
}
Or you can use ProcessBuilder for the same task
public class Main {
public static void main(String[] args) throws java.io.IOException, java.lang.InterruptedException {
// Create ProcessBuilder instance for UNIX command ls -l
java.lang.ProcessBuilder processBuilder = new java.lang.ProcessBuilder("ls", "-l");
// Create an environment (shell variables)
java.util.Map env = processBuilder.environment();
env.clear();
env.put("COLUMNS", "3");
processBuilder.directory(new java.io.File("/Users"));
java.lang.Process p = processBuilder.start();
}
}

How can i execute batch file content in java on a server without window popping up

The uploaded Screenshot conatains the start_client.bat file content, viewed in notepad++ editor.
Currently am invoking start_client.bat on local machine it works fine but when the same bat file is invoked on server it pops up a window on server and it needs manual closure after execution. Any way to force bat file execution on server without window poppping up.
private void invokeSeagull(String flag) throws Exception
{
String path="";
if(flag.equals("Start"))
{
path="cmd /c start D:/Seagull/TIB/start_client.bat";
}
if(flag.equals("Stop"))
{
path="cmd /c start D:/Seagull/TIB/stop_client.bat";
}
try {
String line;
Process p = Runtime.getRuntime().exec(path);
p.waitFor();
BufferedReader bri = new BufferedReader
(new InputStreamReader(p.getInputStream()));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p.getErrorStream()));
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
p.waitFor();
System.out.println("Done.");
}
catch (Exception err) {
err.printStackTrace();
}
}
This code snippet should run batch file, of course if you use Windows.
Runtime.getRuntime().exec("cmd /c start {pathToFile}");
As pointed out be ssedano the correct way to execute shell commands in Java is the Process-builder:
// Just the name of an executable is enough
final ProcessBuilder pb = new ProcessBuilder( "test.bat" );
pb.redirectError( Redirect.INHERIT );
pb.redirectOutput( Redirect.INHERIT );
System.out.println( String.format( "***** Running Process %s OUTPUT:", pb.command().toString() ) );
final Process process = pb.start();
process.getOutputStream().close();
final int returnCode = process.waitFor();
System.out.println( "***** Process Exited with Returncode: " + returnCode );
You can just redirect STDERR and STDOUT of the bat-file, so you will get all output in the Server-Output console. And you should close STDIN of the bat-file, so it will exit and not get stuck on the pause command at the end!
You could use the new in Java 7 ProcessBuilder
A simple example:
String[] command = {"CMD", "/C", "dir"};
ProcessBuilder probuilder = new ProcessBuilder(command);
// Set up your work directory
probuilder.directory(new File("c:\\stackoverflow"));
Process process = probuilder.start();
// Read output
try (InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);)
{
String line;
System.out.printf("Output of running %s is:\n", Arrays.toString(command));
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
// Wait to get exit value
int exitValue = process.waitFor();
}
catch (Exception e)
{
// Fail
}
This should run in the silent mode :
Runtime.getRuntime().exec(new String[] {"cmd", "/pathto/start_client.bat"});

Not able to capture output of "who -m" command in JAVA

I want to get the IP address of logged in user of the telnet session
So I have written the following code:
Process p1 = Runtime.getRuntime().exec(new String[] {"/usr/bin/who", "-m"});
p1.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p1.getInputStream()));
String line = reader.readLine();
System.out.println("line=" + line);
reader.close();
But I am getting the output as "null".
Where as expected output is:
linus pts/1 Dec 10 03:48 (172.21.235.48)
In this case you shouldn't pass the -m option.
This works for me :
Process p1 = Runtime.getRuntime().exec(new String[] {"/usr/bin/who"});
Try to consume the input stream from the process before calling waitFor().
You can create a shell script which will receive parameter (option) from your java program.
Then you can run your shell script from java like this -
ProcessBuilder pb = new ProcessBuilder("/PATH/test.sh","-m");
String line;
Process process=pb.start();
java.io.InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
return br;
Now in test.sh, you cab grab the argument and run the command -
/usr/bin/who $1 (needs to check, not sure)
Hope this helps.
Thanks guys for the replies.
From the reply of "dystroy" I understood that -m was creating problem.
I tried --m and it worked :)
Please try this code. It's working for me and returns the same output as who -m UNIX command.
import java.io.*;
public class UserPB
{
public static void main(String[] args)
{
try {
// ProcessBuilder pb = new ProcessBuilder("/u01/app/chdir/user.sh");
ProcessBuilder pb = new ProcessBuilder("who");
Process p;
p = pb.start();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println("Your Host Details--->"+input.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Running Command Line in Java [duplicate]

This question already has answers here:
Executing a Java application in a separate process
(9 answers)
Closed 7 years ago.
Is there a way to run this command line within a Java application?
java -jar map.jar time.rel test.txt debug
I can run it with command but I couldn't do it within 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
You can also watch the output like this:
final Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null)
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p.waitFor();
And don't forget, if you are running a windows command, you need to put cmd /c in front of your command.
EDIT: And for bonus points, you can also use ProcessBuilder to pass input to a program:
String[] command = new String[] {
"choice",
"/C",
"YN",
"/M",
"\"Press Y if you're cool\""
};
String inputLine = "Y";
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
writer.write(inputLine);
writer.newLine();
writer.close();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
This will run the windows command choice /C YN /M "Press Y if you're cool" and respond with a Y. So, the output will be:
Press Y if you're cool [Y,N]?Y
To avoid the called process to be blocked if it outputs a lot of data on the standard output and/or error, you have to use the solution provided by Craigo. Note also that ProcessBuilder is better than Runtime.getRuntime().exec(). This is for a couple of reasons: it tokenizes better the arguments, and it also takes care of the error standard output (check also here).
ProcessBuilder builder = new ProcessBuilder("cmd", "arg1", ...);
builder.redirectErrorStream(true);
final Process process = builder.start();
// Watch the process
watch(process);
I use a new function "watch" to gather this data in a new thread. This thread will finish in the calling process when the called process ends.
private static void watch(final Process process) {
new Thread() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
import java.io.*;
Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
Consider the following if you run into any further problems, but I'm guessing that the above will work for you:
Problems with Runtime.exec()
what about
public class CmdExec {
public static Scanner s = null;
public static void main(String[] args) throws InterruptedException, IOException {
s = new Scanner(System.in);
System.out.print("$ ");
String cmd = s.nextLine();
final Process p = Runtime.getRuntime().exec(cmd);
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p.waitFor();
}
}
Have you tried the exec command within the Runtime class?
Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug")
Runtime - Java Documentation
Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");

How to Execute Windows Commands Using Java - Change Network Settings

In Java, I want to be able to execute a Windows command.
The command in question is netsh. This will enable me to set/reset my IP address.
Note that I do not want to execute a batch file.
Instead of using a batch file, I want to execute such commands directly. Is this possible?
Here is my implemented Solution for Future Reference:
public class JavaRunCommand {
private static final String CMD =
"netsh int ip set address name = \"Local Area Connection\" source = static addr = 192.168.222.3 mask = 255.255.255.0";
public static void main(String args[]) {
try {
// Run "netsh" Windows command
Process process = Runtime.getRuntime().exec(CMD);
// Get input streams
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// Read command standard output
String s;
System.out.println("Standard output: ");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// Read command errors
System.out.println("Standard error: ");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
Runtime.getRuntime().exec("netsh");
See Runtime Javadoc.
EDIT: A later answer by leet suggests that this process is now deprecated. However, as per the comment by DJViking, this appears not to be the case: Java 8 documentation. The method is not deprecated.
Use ProcessBuilder
ProcessBuilder pb=new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process process=pb.start();
BufferedReader inStreamReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
while(inStreamReader.readLine() != null){
//do something with commandline output.
}
You can run the command with Runtime.getRuntime().exec("<command>") (eg. Runtime.getRuntime().exec("tree")). But, this will only run executables found in path, not commands like echo, del, ... But only stuff like tree.com, netstat.com, ... To run regular commands, you will have to put cmd /c before the command (eg Runtime.getRuntime().exec("cmd /c echo echo"))
public static void main(String[] args) {
String command="netstat";
try {
Process process = Runtime.getRuntime().exec(command);
System.out.println("the output stream is "+process.getOutputStream());
BufferedReader reader=new BufferedReader( new InputStreamReader(process.getInputStream()));
String s;
while ((s = reader.readLine()) != null){
System.out.println("The inout stream is " + s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
This works.
Runtime#exec().

Categories

Resources