Runtime
直接使用 docker exec mysql mysqldump -u%s -p%s cblog > %s
(%s是需要填充的数据),命令无法执行并且不会报错,需要使用字符串数组加入"sh", “-c”,具体代码示例:
/**
* MySQL数据备份
*
* @param dataPath 备份文件的保存路径
* @throws IOException
*/
private void backupData(String dataPath) throws IOException {
long start = System.currentTimeMillis();
String cmd = String.format("docker exec mysql mysqldump -u%s -p%s cblog > %s", dataSourceProperties.getUsername(), dataSourceProperties.getPassword(), dataPath);
String[] cmds = {"sh", "-c", cmd};
log.debug("欲执行命令:{}", cmd);
try (InputStream inputStream = Runtime.getRuntime().exec(cmds).getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);) {
String line = bufferedReader.readLine();
while (line != null) {
log.debug(line);
line = bufferedReader.readLine();
}
}
long end = System.currentTimeMillis();
log.info("mysql备份命令执行成功,耗时:{}ms", end - start);
}