try {
try {
String[] command = {"cmd.exe", "/C", "Start", "D:\\test.bat"};
Runtime r = Runtime.getRuntime();
Process p = r.exec(command);
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Error" +"Execution!","Error",JOptionPane.ERROR_MESSAGE);
}
} catch (IOException ex) {
Logger.getLogger(DBBackUp.class.getName()).log(Level.SEVERE, null, ex);
}
When I run this code, I got only command promt. .bat file is not running.
How can I execute the batch file using this code?
Thank in Advance
Consider
using Apache Commons Exec.
let your "test.bat" be like this:
dir
pause
then you can execute this batch file as follows:
try
{
Runtime r = Runtime.getRuntime();
Process p = r.exec("rundll32 url.dll,FileProtocolHandler " + "D:\\test.bat");
p.waitFor();
}catch(Exception ex){ex.printStackTrace();}
You can try something like this:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class BatchExecuteService {
public static void main(String[] args) {
BatchExecuteService batchExecuteService = new BatchExecuteService();
batchExecuteService.run();
}
public void run() {
try {
String cmds[] = {"D:\\test.bat"};
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(cmds);
process.getOutputStream().close();
InputStream inputStream = process.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputStream);
BufferedReader bufferedrReader = new BufferedReader(inputstreamreader);
String strLine = "";
while ((strLine = bufferedrReader.readLine()) != null) {
System.out.println(strLine);
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
Related
A very simple code running in the debugging mode perfectly but not working after installation of exe, giving no response/result in return. even no errors to trace.
After building a .exe and installing on my PC its happening, very strange.
tried process builder but the same thing, anyway to check/trace it. maybe paths ?
StringBuilder b = new StringBuilder();
Process p = Runtime.getRuntime().exec("wmic diskdrive get signature");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
b.append(line);
}
Please note: CMD /c before commands also return an empty response in actual env.
An internal windows command with arguments, like "wmic diskdrive ..."
can be executed easily by wrapping it up inside a cmd window.
Here is the working code snippet for running the wmic command encapsulated in a cmd window:
import java.io.*;
public class Wmic {
public static void main(String[] args) {
StringBuilder b = new StringBuilder();
try {
// Initialize a process object to run
// wmic command and its parameters
// inside a cmd window
Process process = Runtime.getRuntime()
.exec("cmd /c C:\\Windows\\System32\\wbem\\WMIC.exe diskdrive get signature");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
b.append(line);
}
} catch (Exception ex) {
b.append(ex.toString());
}
System.out.println("Output: \n" + b.toString());
}
}
Output:
>javac Wmic.java
>java Wmic
Output:
Signature
More information:
https://mkyong.com/java/how-to-execute-shell-command-from-java/
The ProcessBuilder constructor takes a list of strings. When using ProcessBuilder to run a command, I separate all the words in the command into separate strings.
I read the output of the process in a separate thread. And I always wait for the command, that I launched via ProcessBuilder, to terminate.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
public class PrcBldTs {
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder("wmic","diskdrive","get","signature");
try {
Process proc = pb.start();
StreamGobbler error = new StreamGobbler(proc.getErrorStream());
StreamGobbler output = new StreamGobbler(proc.getInputStream());
Thread stdout = new Thread(output);
Thread stderr = new Thread(error);
stdout.start();
stderr.start();
int result = proc.waitFor();
stdout.join();
stderr.join();
System.out.println("Exit status = " + result);
if (result != 0) {
System.out.println(error.getContents());
}
else {
System.out.println(output.getContents());
}
}
catch (IOException | InterruptedException x) {
x.printStackTrace();
}
}
}
class StreamGobbler implements Runnable {
private BufferedReader reader;
private StringWriter sw;
public StreamGobbler(InputStream is) {
InputStreamReader isr = new InputStreamReader(is);
reader = new BufferedReader(isr);
sw = new StringWriter();
}
public String getContents() {
return sw.toString();
}
public void run() {
try {
String line = reader.readLine();
while (line != null) {
sw.append(line);
sw.append(System.lineSeparator());
line = reader.readLine();
}
}
catch (IOException xIo) {
throw new RuntimeException(xIo);
}
}
}
Running the above code gave me the following output.
Exit status = 0
Signature
1145609371
I am currently trying to find a way to flush my dns cache through a program in java. When I execute my code, the command prompt appears but i cant figure out how to get my code to execute.
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm) {
istrm_ = istrm;
ostrm_ = ostrm;
}
public void run() {
try
{
final byte[] buffer = new byte[1024];
for (int length = 0; (length = istrm_.read(buffer)) != -1; )
{
ostrm_.write(buffer, 0, length);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private final OutputStream ostrm_;
private final InputStream istrm_;
}
public class FlushCommand {
FlushCommand(InputStream errorStream, PrintStream err) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
This is main method below:
String command = "cmd /c start cmd.exe";
{
};
Process p = null;
try {// Execute command
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();
p = Runtime.getRuntime().exec(command);
} catch (IOException ex) {
Logger.getLogger(FlushDNS.class.getName()).log(Level.SEVERE, null, ex);
}
new Thread((Runnable) new FlushCommand(p.getErrorStream(), System.err)).start();
new Thread((Runnable) new FlushCommnad(p.getInputStream(), System.out)).start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("dir c:\\ /A /Q");
stdin.println("ipconfig/flushdns");
// write any other commands you want here
stdin.close();
int returnCode = 0;
try {
returnCode = p.waitFor();
} catch (InterruptedException ex) {
Logger.getLogger(FlushDNS.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Return code = " + returnCode);
}
Why don't you start from very basic?
Your command is just opening a command window. If I remember correctly, the following should flush your dns and remain unclosed (cmd will not be automatically closed).
String command = "cmd.exe /c start cmd.exe /c start ipconfig /flushdns";
try{
Runtime.getRuntime.exec(command);
catch(...){}
I have to check my old codes in my computer to make sure but I'd suggest you to start from basic and then do multi-threading etc.
Alternatively, you can use process builder to create your command.
import java.io.*;
public class Clasa {
public static void main(String args[]) {
try {
Runtime rt = Runtime.getRuntime();
String comand = "net start MySQL55";
Process pr = rt.exec(" cmd.exe /C " + "net start MySQL55");
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();
}
}
}
I try this and gives me the next error code: Exited with error code 2
I want to execute android shell command from my android app to execute a uiautomator test jar.
i have tried following options. but neither of them is working for me...
public void execute(String shellcommand) {
Runtime rt = Runtime.getRuntime();
Process p = r.exec(new String[]{"/system/bin/sh", "-c", shellcommand});
}
Also tried...
public void execute(String shellcommand) {
Process su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
outputStream.writeBytes(shellcommand + "\n");
outputStream.flush();
outputStream.writeBytes("exit\n");
outputStream.flush();
su.waitFor();
}
Please tell what mistake i m doing?
Android 5.0 solved your problem. Here is new API using which you can execute shell commands.Check here : executeShellCommand (String command)
Enjoy!!!
Try this, i added an output reading process also. But you'll need to cut up your shell command:
ProcessBuilder pb = new ProcessBuilder("adb", "shell", "uiautomator", "runtest", "/data/local/tmp/MyJar.jar", "-c", "com.my.test.Class#testmethod", "-e someparameter someparameterName");
Process pc;
try {
pc = pb.start();
InputStream stdin = pc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
InputStreamReader esr = new InputStreamReader(pc.getErrorStream());
BufferedReader errorReader = new BufferedReader(esr);
pc.waitFor();
} catch (IOException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Assert.fail(e.getMessage());
}
I have a VBS file test.vbs in C:/work/selenium/chrome/ and I want to run it from my Java program, so I tried this but with no luck:
public void test() throws InterruptedException {
Runtime rt = Runtime.getRuntime();
try {
Runtime.getRuntime().exec( "C:/work/selenium/chrome/test.vbs" );
}
catch( IOException e ) {
e.printStackTrace();
}
}
If I try to run some exe file with this method it runs well, but when I try to run a VBS file it says "not a valid win32 application".
Any idea how to run a VBS file from Java?
public static void main(String[] args) {
try {
Runtime.getRuntime().exec( "wscript D:/Send_Mail_updated.vbs" );
}
catch( IOException e ) {
System.out.println(e);
System.exit(0);
}
}
This is working fine where Send_Mail_updated.vbs is name of my VBS file
A vbs-Script isn't natively executable like a bat, cmd or exe-Program. You have to start the interpreter (vbs.exe?) and hand your script over as a parameter:
String script = "C:\\work\\selenium\\chrome\\test.vbs";
// search for real path:
String executable = "C:\\windows\\...\\vbs.exe";
String cmdArr [] = {executable, script};
Runtime.getRuntime ().exec (cmdArr);
Runtime.getRuntime().exec( "cscript E:/Send_Mail_updated.vbs" )
try {
Runtime.getRuntime().exec(new String[] {
"wscript.exe", "C:\\path\\example.vbs"
});
} catch (Exception ex) {
ex.printStackTrace();
}
You can use the code above to run vbs file.
The complete code here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class VBTest {
public static void main(String[] args) {
try {
String line;
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;
Process process = Runtime.getRuntime().exec( "cscript E:/Send_Mail_updated.vbs" );
stdin = process.getOutputStream ();
stderr = process.getErrorStream ();
stdout = process.getInputStream ();
// "write" the parms into stdin
line = "param1" + "\n";
stdin.write(line.getBytes() );
stdin.flush();
line = "param2" + "\n";
stdin.write(line.getBytes() );
stdin.flush();
line = "param3" + "\n";
stdin.write(line.getBytes() );
stdin.flush();
stdin.close();
// clean up if any output in stdout
BufferedReader brCleanUp = new BufferedReader (new InputStreamReader (stdout));
while ((line = brCleanUp.readLine ()) != null) {
System.out.println ("[Stdout] " + line);
}
brCleanUp.close();
// clean up if any output in stderr
brCleanUp =
new BufferedReader (new InputStreamReader (stderr));
while ((line = brCleanUp.readLine ()) != null) {
System.out.println ("[Stderr] " + line);
}
brCleanUp.close();
}
catch( IOException e ) {
System.out.println(e);
//System.exit(0);
}
}
}