备份mysql使用的是cmd命令:mysqldump -h xx -uxx -pxx --databases xx > xx
xx:需要连接数据库的ip地址
xx:当前连接数据库的用户名
xx:当前连接数据库的密码
xx:想要备份的数据库名称
xx:想要保存文件的位置和保存文件类型
举例:mysqldump -h 127.0.0.1 -uroot -p123 --databases text > D:/text.sql
一:备份mysql数据库
public class BackupDb {
Properties properties = new Properties();
// 保存备份文件的路径及名称
static String path = "D://backup//db//"+System.currentTimeMillis()+".sql";
public BackupDb() throws IOException, MessagingException {
properties.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream("timer.properties"),"UTF-8"));
// 读取配置文件中的信息
// MySql的安装bin目录路径和dump等参数
String sqlurl = properties.getProperty("sqlurl");
// 备份数据库
backup(sqlurl);
}
public static void backup(String sqlurl) {
try {
Runtime rt = Runtime.getRuntime();
//执行cmd命令
Process child = rt.exec(sqlurl);
// 设置导出编码为utf-8。这里必须是utf-8
InputStream in = child.getInputStream();// 控制台的输出信息作为输入流
InputStreamReader xx = new InputStreamReader(in, "utf-8");
// 设置输出流编码为utf-8。这里必须是utf-8,否则从流中读入的是乱码
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();
//导出文件到自定义目录
FileOutputStream fout = new FileOutputStream(path);
OutputStreamWriter writer = new OutputStreamWriter(fout, "utf-8");
writer.write(outStr);
writer.flush();
in.close();
xx.close();
br.close();
writer.close();
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
BackupDb testMysql;
try {
testMysql = new BackupDb();
testMysql.backup("D://Program Files//MySQL//MySQL Server 5.7//bin//mysqldump -h 127.0.0.1 -uroot -p123 --databases text");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
备份完成后,可以到自定义的保存目录下查看备份的文件。
二:压缩文件并邮件
压缩文件参照:https://www.cnblogs.com/lihaiming93/p/8098255.html
public class Compress {
/**
* s 压缩文件
*
* @param srcFilePath
* 压缩源路径
* @param destFilePath
* 压缩目的路径
*/
public static void compress(String srcFilePath, String destFilePath) {
File src = new File(srcFilePath);
if (!src.exists()) {
throw new RuntimeException(srcFilePath + "不存在");
}
File zipFile = new File(destFilePath);
try {
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
String baseDir = "";
compressbyType(src, zos, baseDir);
zos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 按照原路径的类型就行压缩。文件路径直接把文件压缩
*
* @param src
* @param zos
* @param baseDir
*/
private static void compressbyType(File src, ZipOutputStream zos, String baseDir) {
if (!src.exists())
return;
// 判断文件是否是文件,如果是文件调用compressFile方法,如果是路径,则调用compressDir方法;
if (src.isFile()) {
// src是文件,调用此方法
compressFile(src, zos, baseDir);
} else if (src.isDirectory()) {
// src是文件夹,调用此方法
compressDir(src, zos, baseDir);
}
}
/**
* 压缩文件
*/
private static void compressFile(File file, ZipOutputStream zos, String baseDir) {
if (!file.exists())
return;
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry entry = new ZipEntry(baseDir + file.getName());
zos.putNextEntry(entry);
int count;
byte[] buf = new byte[1024];
while ((count = bis.read(buf)) != -1) {
zos.write(buf, 0, count);
}
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 压缩文件夹
*/
private static void compressDir(File dir, ZipOutputStream zos, String baseDir) {
if (!dir.exists())
return;
File[] files = dir.listFiles();
if (files.length == 0) {
try {
zos.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator));
} catch (IOException e) {
e.printStackTrace();
}
}
for (File file : files) {
compressbyType(file, zos, baseDir + dir.getName() + File.separator);
}
}
}
压缩之后,能查看到.zip文件
在邮件:
public class SendEmails {
public SendEmails() {
// TODO Auto-generated constructor stub
}
/**
* enable:是否校验(或者授权):true
* debug:是否打印控制台消息
* sendAddress:发件人地址
* to:邮件接收者地址
* subject:邮件主题
* context:邮件内容
* path:文本路径
* owner:自己的邮箱账号
* ownerStmp:自己邮箱的stmp客户端授权码
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public void sendEmails(String enable, String debug, String owner, String to, String subject, String context,
String path, String ownerStmp) throws MessagingException, UnsupportedEncodingException {
Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");// 连接协议
properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
properties.put("mail.smtp.port", 465);// 端口号
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.enable", enable);// 设置是否使用ssl安全连接 ---一般都使用
properties.put("mail.debug", debug);// 设置是否显示debug信息 true 会在控制台显示相关信息
// 得到回话对象
Session session = Session.getInstance(properties);
// 获取邮件对象
Message message = new MimeMessage(session);
// 设置发件人邮箱地址
message.setFrom(new InternetAddress(owner));
// 设置收件人邮箱地址
message.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress(to) });
// 设置邮件标题
message.setSubject(subject);
// 创建消息部分
BodyPart messageBodyPart = new MimeBodyPart();
// 消息
messageBodyPart.setText(context);
// 创建多重消息
Multipart multipart = new MimeMultipart();
// 设置文本消息部分
multipart.addBodyPart(messageBodyPart);
// 附件部分
messageBodyPart = new MimeBodyPart();
// 设置要发送附件的文件路径
DataSource source = new FileDataSource(path);
messageBodyPart.setDataHandler(new DataHandler(source));
//设置当前发送邮件时间
message.setSentDate(new Date());
// messageBodyPart.setFileName(filename);
// 处理附件名称中文(附带文件路径)乱码问题
messageBodyPart.setFileName(MimeUtility.encodeText(path));
multipart.addBodyPart(messageBodyPart);
// 发送完整消息
message.setContent(multipart);
// 得到邮差对象
Transport transport = session.getTransport();
// 连接自己的邮箱账户
transport.connect(owner, ownerStmp);// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
// 发送邮件
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
}
自己邮箱的stmp客户端授权码:需要打开自己的QQ邮箱 > 设置 >账户
生成的授权码,则是当前需要的授权码。