环境要求:JDK1.7? TOMCAT8和mySQL数据库
其中另外需要辅助jar包为的jodd-core-5.0.0.jar
其下载地址为:https://mvnrepository.com/artifact/org.jodd/jodd-core
下面直接上代码:
前台JSP界面中主要代码为:
<a class="button bg-main icon-check-square-o"
href="<%=path %>/exportSQL" style="margin:80px 0px;"> 导出</a>
控制层代码为:
@RequestMapping("/exportSQL")
@ResponseBody
public void exportSQL(HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException {
int beginIndex = dbURL.lastIndexOf("/") + 1;
int endIndex = dbURL.indexOf("?");
//截取,获得数据库名字
String databaseName = dbURL.substring(beginIndex, endIndex);
// 设置导出编码为utf8。这里必须是utf8。cmd命令,-u和-p后边没有空格
String cmd = "mysqldump -u" + dbUser + " -p" + dbPwd + " -hlocalhost --set-charset=utf8 --databases " + databaseName;
try {
Runtime runtime = Runtime.getRuntime();
// 调用 MySQL 的 CMD
Process child = runtime.exec(cmd);
// 把进程执行中的控制台输出信息写入.sql文件,即生成了备份文件。注:如果不对控制台信息进行读出,则会导致进程堵塞无法运行
InputStream in = child.getInputStream();// 控制台的输出信息作为输入流
InputStreamReader xx = new InputStreamReader(in, "utf8");// 设置输出流编码为utf8。这里必须是utf8,否则从流中读入的是乱码
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
// 组合控制台输出信息字符串
BufferedReader br = new BufferedReader(xx);
while ((inStr = br.readLine()) != null) {
sb.append(inStr + "\r\n");
}
outStr = sb.toString();
//取得系统缓存目录
String tmpDir = System.getProperty("java.io.tmpdir");
//获得当前时间戳
String date = UUIDUtil.getTimeString();
String localFilePath = tmpDir + "db_shms-" + date + ".sql";
File localFile = new File(localFilePath);
byte[] data = outStr.getBytes("UTF-8");
try (final OutputStream output = new FileOutputStream(localFile)) {
IOUtils.write(data, output);
}
File zipFile = ZipUtil.zip(localFile);
byte[] zipData;
try (final FileInputStream inputStream = new FileInputStream(zipFile)) {
zipData = IOUtils.toByteArray(inputStream);
}
//设置响应相关的参数
response.setContentType("application/zip");
final String fileName = "db_shms-" + date + ".zip";
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
final ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(zipData);
in.close();
xx.close();
br.close();
outputStream.flush();
outputStream.close();
//删除缓存目录的缓存文件,sql文件和zip文件
localFile.delete();
zipFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
|