I am trying to backup MySQL DB using ProcessBuilder
in Java but, I get this error.
"!Cannot run program "C:\Program Files\MySQL\MySQL Server 5.5\bin": CreateProcess error=5, Access is denied".
Here is my Code.
public static String backupDb() {
String resp=null;
try {
System.out.println("Started........");
ProcessBuilder builder = new ProcessBuilder("C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin", "mysqldump -u root -pmypass mydb> c:\\backup\\mybackup.sql");
builder.redirectErrorStream(true);
Process p = builder.start();
} catch(Exception e) {
resp="!"+e.getMessage();
}
return resp;
}
Where could I be going wrong?
There are a few things you have to do for this to work:
>
) won't work. C:\\foo\bar\foobar\backup.sql
but one of the C:\\foo
, C:\\foo\\bar
, C:\\foo\\bar\\foobar
folders doesn't exist, you'll get an error" "
, else you'll get awkward errors, such as : 'C:\Program' is not recognized as an internal or external command
Here is a tested version including all the things above. I'm passing the filepath as a parameter, because it's more flexible this way.
public static void backupDb(final String mysqlDumpFilePath)
throws IOException, InterruptedException {
String folderPath = mysqlDumpFilePath.substring(0, mysqlDumpFilePath.lastIndexOf("\\"));
File folder = new File(folderPath);
if (!folder.exists()) {
folder.mkdirs(); // 2
}
File f = new File(mysqlDumpFilePath);
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "C:\\\"Program Files\"\\MySQL\\\"MySQL Server 5.5\"\\bin\\mysqldump -u root -pmypass mydb > "
+ f.getAbsolutePath()); //1 & 3
Process exec = builder.start();
int retCode = exec.waitFor();
if (retCode != 0) { //4
// something went wrong
InputStream errorStream = exec.getErrorStream();
byte[] buffer = new byte[errorStream.available()];
errorStream.read(buffer);
System.out.println(new String(buffer));
}
}