日期:2014-05-16  浏览次数:20756 次

java 驱动mysqldump 进行自动备份
import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;

public class MysqlDump1 {
private String ip;
private String port;
private String database;
private String user;
private String pass;
private String path;


public MysqlDump1(String ip, String port, String database, String user,
String pass, String path) {
super();
this.ip = ip;
this.port = port;
this.database = database;
this.user = user;
this.pass = pass;
this.path = path;
}

public String getIp() {
return ip;
}

public void setIp(String ip) {
this.ip = ip;
}

public String getPort() {
return port;
}

public void setPort(String port) {
this.port = port;
}

public String getDatabase() {
return database;
}

public void setDatabase(String database) {
this.database = database;
}

public String getUser() {
return user;
}

public void setUser(String user) {
this.user = user;
}

public String getPass() {
return pass;
}

public void setPass(String pass) {
this.pass = pass;
}

public String getPath() {
return path;
}

public void setPath(String path) {
this.path = path;
}

public void export(){
String dumpCommand = "mysqldump " + database + " -h " + ip + " -u " + user +" -p" + pass;
Runtime rt = Runtime.getRuntime();
File test=new File(path);
PrintStream ps;

try{
Process child = rt.exec(dumpCommand);
ps=new PrintStream(test);
InputStream in = child.getInputStream();
int ch;
while ((ch = in.read()) != -1) {
ps.write(ch);
System.out.write(ch); //to view it by console
}

InputStream err = child.getErrorStream();
while ((ch = err.read()) != -1) {
System.out.write(ch);
}
}catch(Exception exc) {
exc.printStackTrace();
}
}

public static void main(String args[]){
MysqlDump1 md=new MysqlDump1("localhost","3306","materials","root","root","E:\\materials.sql");
md.export();
}
}