I am trying to dump a MySQL database within my Java application the following way:
String[] command = new String[] {"cmd.exe", "/c", "C:/mysql/mysqldump.exe" --quick --lock-tables --user=\"root\" --password=\"mypwd\" mydatabase > \"C:/mydump.sql\""};
Process process = Runtime.getRuntime().exec(command);
int exitcode = process.waitFor();
The process fails with exit-code 6. I somewhere read that the operand ">" is not correctly interpreted and there was the hint to use "cmd.exe /c" as prefix. But it still doesn't work.
Any ideas?
Yes, you are right , some days ago I made class for exporting DataBase from MySQL...
You coud read output sream from console and then write to file
String[] command = new String[] {"cmd.exe", "/c", "\"C:/Program Files/MySQL/MySQL Server 5.6/bin/mysqldump.exe\" --quick --lock-tables --user=\"root\" --password=\"mypwd\" mydatabase "};
Process process = Runtime.getRuntime().exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line); //there you can write file
}
input.close();
Best Regards
Okay here's the final solution. You need to put the "process-reader to file-writer" code into a separate thread and finally wait for the process object to be finished:
// define backup file
File fbackup = new File("C:/backup.sql");
// execute mysqldump command
String[] command = new String[] {"cmd.exe", "/c", "C:/path/to/mysqldump.exe --quick --lock-tables --user=myuser --password=mypwd mydatabase"};
final Process process = Runtime.getRuntime().exec(command);
// write process output line by line to file
if(process!=null) {
new Thread(new Runnable() {
#Override
public void run() {
try{
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new DataInputStream(process.getInputStream())));
BufferedWriter writer = new BufferedWriter(new FileWriter(fbackup))) {
String line;
while((line=reader.readLine())!=null) {
writer.write(line);
writer.newLine();
}
}
} catch(Exception ex){
// handle or log exception ...
}
}
}).start();
}
if(process!=null && process.waitFor()==0) {
// success ...
} else {
// failed
}
On Linux you can directly re-direct the output of the command to a file by using ">" as usual... (and also on Mac OS X I think). So no need for the thread. Generally, please avoid white spaces in your path to the mysqldump/mysqldump.exe file!
Related
I'm currently making firefox addon development GUI tool using Java. However I am stuck when trying to get output of a .bat file.
When I run .bat file using java I can see the output, but there are 3 commands written in the bat file. When first command executes I can get the output simultaneously. But when it execute second command output not coming. And when .bat file exist I get all the output which didn't come simultaneously.
I'm getting output immediately when it execute:
call "C:\mozilla-build\addon-sdk-1.16\bin\activate.bat
But I'm not getting output simultaneously for following command:
call cfx run
But I know it's executing because firefox window pops up. I get all the output suddenly when I execute proc.destroy();
This is my bat file:
#echo off
call %1
cd C:\Users\Madhawa.se\Desktop\workingfox\beauty
call cfx run
pause
This is my Java code:
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
Runtime rt = Runtime.getRuntime();
String[] commands = {"C:\\Users\\Madhawa.se\\Desktop\\workingfox\\runner\\foxrun.bat", "C:\\mozilla-build\\addon-sdk-1.16\\bin\\activate.bat"};
proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
proc.waitFor();
System.out.println("success");
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
t.start();
How to get output immediately and why it acts differently for this command?
i was able to fix it using process builder instead of runtime.exec .and inheriteIo doesn't work .it blocks the realtime output
Thread t = new Thread(new Runnable() {
private String s;
#Override
public void run() {
try {
Component selectedComponent = jTabbedPane2.getSelectedComponent();
if (selectedComponent instanceof MyTextArea) {
String response = "";
System.out.println("yes");
MyTextArea temptextarea = (MyTextArea) selectedComponent;
String xpiPath = new File(temptextarea.getNameX()).getParentFile().getPath();
String[] commands = {"C:\\Users\\Madhawa.se\\Desktop\\workingfox\\runner\\foxrun.bat", "C:\\mozilla-build\\addon-sdk-1.16\\bin\\activate.bat
ProcessBuilder process = new ProcessBuilder(commands);
process.redirectErrorStream(true);
Process shell = process.start();
//shell.waitFor();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(shell.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(shell.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println("s:" + s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println("w:" + s);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
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"});
public static void main(String[] args) throws Exception {
System.setOut(new PrintStream(
new FileOutputStream("/home/main/smt/output/out.txt")));
try {
String line;
Process p = Runtime.getRuntime().exec(
"/home/main/smt/tools/moses-2010-08-13/moses/moses-cmd/src/moses " +
"-f /home/main/smt/work/model/moses.ini " +
"< /home/main/smt/work/corpus/dataset.en" );
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()) );
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
catch (Exception e) {
// ...
}
}
the command
home/main/smt/tools/moses-2010-08-13/moses/moses-cmd/src/moses
-f /home/main/smt/work/model/moses.ini
< /home/main/smt/work/corpus/dataset.en
>/home/main/smt/output/out.txt
gets executed in terminal of Linux and out.txt is created. But in java no out.txt is created.
dataset.en is the input file. Using exe moses which is in src and moses.ini in model the content in dataset.en gets translated and saved in out.txt.
But here while running this code no out.txt is created. I removed saving output in a file from the command eventhough nothing gets displayed in the console. If i change Process p = Runtime.getRuntime().exec(ls) its working fine.
Shell can interpret the redirection and arguments. You should instead try
String[] cmd = {"/bin/ksh", "-c", "yourcommand < infile"};
Process process = Runtime.getRuntime().exec(cmd);
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");
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().