public class DumpFileClass{
public static boolean importDump(String host, String username, String password, String database, String dumpFilePath) {
String mysqlCommand = "mysql -h " + host + " -u " + username + " -p" + password +" " + database + " < " + dumpFilePath;
System.out.println(mysqlCommand);
try {
Process process = Runtime.getRuntime().exec(mysqlCommand);
logger.trace(process);
int exitCode = process.waitFor();
logger.trace(exitCode);
System.out.println(exitCode);
return exitCode == 0;
} catch (IOException | InterruptedException e) {
e.printStackTrace();
return false;
}
}
}
您可以通过写入进程输入流来避免对 shell 的依赖。还要避免依赖于将数据库名称参数传递给
mysql
,因为这在恢复转储时通常不相关:
public static boolean importDump(String host, String username, String password,
String dumpFilePath) {
boolean result = false;
String[] mysqlCommand = { "mysql", "-h", host, "-u", username, "-p" + password };
try {
ProcessBuilder pb = new ProcessBuilder(mysqlCommand).redirectError(Redirect.INHERIT).redirectOutput(Redirect.INHERIT);
Process process = pb.start();
try (InputStream in = Files.newInputStream(Path.of(dumpFilePath));
OutputStream out = process.getOutputStream()) {
in.transferTo(out);
}
logger.trace(process);
int exitCode = process.waitFor();
logger.trace(exitCode);
result = (exitCode == 0);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}