// 演示: 备份MySQL数据库到Linux下/jyd/dbBack/*.sql目录。 public static void backup(HttpServletRequest request, HttpServletResponse response) { OutputStream out = null; // 程序处理器 Process process = null; InputStream inputStream = null; try { // 清除空白行 response.reset(); // 生成日期格式的文件名 String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())+".sql"; // 设置响应的头信息 response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); response.setHeader("Content-Type", "text/xml;charset=UTF-8"); // 创建执行系统命令的实例 Runtime rt = Runtime.getRuntime(); // 指定Linux下的文件目录 String filePath = "/jyd/dbBack/"+fileName; // 处理器执行mysql数据库备份的命令 process = rt.exec(new String[]{ "/bin/sh", "-c", "/usr/local/mysql-5.5.62/bin/mysqldump -uroot -proot --databases jydcloud_oa>"+filePath }); // waitFor():程序执行完毕; 0成功 if(process.waitFor()==0){ // 创建输入流时指定需要读取的文件路径 // (注意): separator拼接路径才有效,直接用字符串表达会抛出FileNotFound String readPath = File.separator + "jyd" + File.separator + "dbBack" + File.separator + fileName; inputStream = new FileInputStream(readPath); int len=0; byte buffer[]=new byte[1024]; out=response.getOutputStream(); while((len=inputStream.read(buffer))!=-1){ out.write(buffer,0,len); } } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e){ e.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if(inputStream!=null){ inputStream.close(); } if (process != null) { process.destroy(); } } catch (IOException e) { e.printStackTrace(); } } }