在后台页面上导出数据库文件,即通过 mysqldump 数据库为 sql 文件,然后下载下来
直接上代码
/*** 下载SQL** @param response* @throws IOException*/@RequestMapping(value = "/exportSql", method = RequestMethod.GET)public void downloadFile(HttpServletResponse response) throws IOException {String exportPath = mysqldump();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");- ``
InputStream f = new FileInputStream(new File(exportPath));response.reset();response.setContentType("application/x-msdownload;charset=utf-8");response.setHeader("Content-Disposition", "attachment;filename=" + sdf.format(new Date()) + ".sql");//下载文件的名称ServletOutputStream sout = response.getOutputStream();BufferedInputStream bis = null;BufferedOutputStream bos = null;try {bis = new BufferedInputStream(f);bos = new BufferedOutputStream(sout);byte[] buff = new byte[2048];int bytesRead;while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {bos.write(buff, 0, bytesRead);}bos.flush();bos.close();bis.close();} catch (final IOException e) {throw e;} finally {if (bis != null) {bis.close();}if (bos != null) {bos.close();}}}- ``
public static String mysqldump() {Runtime runtime = Runtime.getRuntime();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");- ``
String exportPath = "/www/mysqldump/" + sdf.format(new Date()) + ".sql";String command = getExportCommand(exportPath);// 这里其实是在命令窗口中执行的 command 命令行try {runtime.exec(command);return exportPath;} catch (IOException e) {e.printStackTrace();}return null;}- ``
// 得到导出数据的命令行语句private static String getExportCommand(String exportPath) {StringBuffer command = new StringBuffer();String username = "root";// 用户名String password = "123456";// 密码String host = "localhost";// 导入的目标数据库所在的主机String port = "3306";// 使用的端口号String exportDatabaseName = "house_key";// 导入的目标数据库的名称String MysqlPath = "/www/server/mysql/bin/"; //路径是mysql中// 注意哪些地方要空格,哪些不要空格command.append(MysqlPath).append("mysqldump -u").append(username).append(" -p").append(password)// 密码是用的小p,而端口是用的大P。.append(" -h").append(host).append(" -P").append(port).append(" ").append(exportDatabaseName).append(" -r ").append(exportPath);return command.toString();