Java服务操作Linux下的MySQL数据库进行备份,界面选择路径进行下载

2 篇文章 0 订阅
1 篇文章 0 订阅
// 演示: 备份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();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值