1.数据库备份的类
package com.dbtool;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
/**
* 实现数据表的备份
* @author whh
*
*/
public class DataBaseTool{
// 读取配置文件中的信息
// MySql的安装bin目录路径和dump等参数
static String sqlurl = GetProperties.getSqlurl();
// 保存备份文件的路径及名称
static String path = GetProperties.getPath();
static String sqlNum = null;
public DataBaseTool() throws IOException {
backup(); // 备份数据库
}
public static void backup() {
try {
// 返回与当前的Java应用程序的运行时对象
Runtime rt = Runtime.getRuntime();
// 调用 调用mysql的安装目录的命令
Process child = rt.exec(sqlurl);
// 设置导出编码为utf-8。这里必须是utf-8
// 把进程执行中的控制台输出信息写入.sql文件,即生成了备份文件。注:如果不对控制台信息进行读出,则会导致进程堵塞无法运行
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();
// 要用来做导入用的sql目标文件:
Date date = new Date();
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
// 注意:sqlNum为一个自定义工具类中的static类型的Date变量,自己设置即可
sqlNum = f.format(date);
path = path.split("-")[0] + "-" + sqlNum + ".sql";
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();
System.out.println("备份数据库成功! "+path);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
2.设置两个任务(sql备份任务和sql文件发送任务)
package com.dbtool;
import java.io.File;
import java.io.IOException;
import java.util.TimerTask;
import org.apache.log4j.Logger;
import com.ftputil.ftpUtil;
import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;
/**
* 设置两个任务
* 1 定时备份
* 2 定时向ftp服务器发送文件
* @author whh
*
*/
public class OperationTimer extends TimerTask{
public void run() {
//实现数据库表的备份
try {
new DataBaseTool();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(60*1000);
//连接ftp服务器发送文件夹
new ftpUtil("ip", "21", "用户名", "密码", new File("D://任务//"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
3.定时启动任务
package com.dbtool;
import java.io.*;
import java.util.*;
/**
* 任务定时
* @author whh
*
*/
public class TimerManager {
//读取配置文件获取间隔时间
private static final long PERIOD_DAY = GetProperties.getDistancetime();
//构造函数进行
public TimerManager() throws IOException {
//获取并处理配置文件中的时间
String backuptime=GetProperties.getBackuptime();
String[] time=backuptime.split(":");
int hour = Integer.parseInt(time[0]);
int minute = Integer.parseInt(time[1]);
int second = Integer.parseInt(time[2]);
//调用util包中的日历,设置时间
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
Date date=calendar.getTime(); //第一次执行定时任务的时间
//如果第一次执行定时任务的时间 小于 当前的时间
//此时要在 第一次执行定时任务的时间 加一天,以便此任务在下个时间点执行。如果不加一天,任务会立即执行。
if (date.before(new Date())) {
date = this.addDay(date, 1);
}
//启动定时器控件
Timer timer = new Timer();
//安排指定的任务在指定的时间开始进行重复的固定延迟执行。
timer.schedule(new OperationTimer(),date,PERIOD_DAY);
}
// 增加或减少天数
public Date addDay(Date date, int num) {
Calendar startDT = Calendar.getInstance();
startDT.setTime(date);
startDT.add(Calendar.DAY_OF_MONTH, num);
return startDT.getTime();
}
}
3.配置文件读取类
package com.dbtool;
import java.io.*;
import java.util.Properties;
public abstract class GetProperties {
private static String sqlurl = "";
private static String path = "";
private static long distancetime = 0;
private static String backuptime = "";
static {
/**通过这个方法只能读取类路径下的properties文件*/
Properties properties = new Properties();
// 使用ClassLoader加载properties配置文件生成对应的输入流
InputStream in = GetProperties.class.getClassLoader().getResourceAsStream("backup.properties");
// 使用properties对象加载输入流
try {
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
//获取key对应的value值
sqlurl = properties.getProperty("sqlurl");
path = properties.getProperty("path");
distancetime = Long.parseLong(properties.getProperty("distancetime"));
backuptime = properties.getProperty("backuptime");
}
public static String getSqlurl() {
return sqlurl;
}
public static void setSqlurl(String sqlurl) {
GetProperties.sqlurl = sqlurl;
}
public static String getPath() {
return path;
}
public static void setPath(String path) {
GetProperties.path = path;
}
public static long getDistancetime() {
return distancetime;
}
public static void setDistancetime(long distancetime) {
GetProperties.distancetime = distancetime;
}
public static String getBackuptime() {
return backuptime;
}
public static void setBackuptime(String backuptime) {
GetProperties.backuptime = backuptime;
}
}
4.配置文件
4.1backup.properties
###mysql备份功能路径和数据库用户名密码###
sqlurl = C:/Program Files (x86)/MySQL/MySQL Server 5.5/bin/mysqldump -uroot -p123 mydb tb_item
###备份的sql路径,必须手动在指定盘符下创建LeaveDatabase目录###
path = D:/LeaveDatabase/tb-.sql
###备份的时间间隔24*60*60*1000=86400000一天###
distancetime = 86400000
###每天启动备份的时间###
backuptime = 12:00:00
4.2 log4j.properties(日志配置文件)
###设置日志级别###
log4j.rootLogger = debug,stdout,D,E
###输出信息到控制台###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
###输出DEBUG级别的日志到 D://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = D://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
###输出ERROR级别的日志到 D://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =D://logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
5 FTP文件上传类
public class ftpUtil {
private static final Logger logger = Logger.getLogger(ftpUtil.class);
private FTPClient client;
private String ROOT_PATH = "content";// FTP服务器根目录的目录名
String host=null;
String port=null;
String username=null;
String password=null;
File dir=null;
public ftpUtil() throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException {
}
/**
*
* @param host ftp服务器ip
* @param port 端口号
* @param username 登陆名
* @param password 密码
* @param dir 上传的本地文件夹
* @throws IllegalStateException
* @throws IOException
* @throws FTPIllegalReplyException
* @throws FTPException
* @throws FTPDataTransferException
* @throws FTPAbortedException
*/
public ftpUtil(String host, String port, String username, String password, File dir){
super();
this.host = host;
this.port = port;
this.username = username;
this.password = password;
this.dir = dir;
//初始化客户端实现登陆
try {
initClient(host, port, username, password);
} catch (IllegalStateException | IOException | FTPIllegalReplyException | FTPException e) {
logger.error(e);
e.printStackTrace();
}
//上传文件夹
try {
uploadDirectory(dir);
} catch (IllegalStateException | IOException | FTPIllegalReplyException | FTPException
| FTPDataTransferException | FTPAbortedException e) {
logger.error(e);
e.printStackTrace();
}
//断开连接
try {
disConnect();
logger.info("退出登陆");
} catch (IllegalStateException | IOException | FTPIllegalReplyException | FTPException e) {
logger.error(e);
e.printStackTrace();
}
}
/**
* 初使化客户端
*
* @param host
* @param port
* @param username
* @param password
* @throws IllegalStateException
* @throws IOException
* @throws FTPIllegalReplyException
* @throws FTPException
*/
public void initClient(String host, String port, String username,
String password) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException {
client = new FTPClient();
System.out.println(">>>>>start connect.......");
try {
client.connect(host, Integer.valueOf(port));
} catch (NumberFormatException | IllegalStateException | IOException | FTPIllegalReplyException
| FTPException e) {
logger.error(e);
e.printStackTrace();
}
System.out.println(">>>>>connect success.......");
System.out.println(">>>>>start login .......");
try {
client.login(username, password);
} catch (IllegalStateException | IOException | FTPIllegalReplyException | FTPException e) {
logger.error(e);
e.printStackTrace();
}
System.out.println(">>>>>login success.......");
System.out.println(">>>>>current directory is.....["
+ client.currentDirectory() + "]");
}
public void setRootPath(String rootPath) {
this.ROOT_PATH = rootPath;
}
/**
* 客户端初使化
*
* @throws FTPException
* @throws FTPIllegalReplyException
* @throws IOException
* @throws IllegalStateException
*/
public void testClient() throws IllegalStateException, IOException,
FTPIllegalReplyException, FTPException {
client = new FTPClient();
System.out.println(">>>>>start connect.......");
client.connect("127.0.0.1", 21);
System.out.println(">>>>>connect success.......");
System.out.println(">>>>>start login .......");
client.login("ISUR", "123");
System.out.println(">>>>>login success.......");
System.out.println(">>>>>current directory is.....["
+ client.currentDirectory() + "]");
}
/**
* 上传整个目录
*
* @param dir
* @throws IOException
* @throws FTPException
* @throws FTPIllegalReplyException
* @throws IllegalStateException
* @throws FTPAbortedException
* @throws FTPDataTransferException
*/
public void uploadDirectory(File dir) throws IOException,
IllegalStateException, FTPIllegalReplyException, FTPException,
FTPDataTransferException, FTPAbortedException {
// 判断本地被上传的目录是否存在
if (!dir.exists()) {
return;
}
// 取在ftp保存的相对路径
String dirs = getSavePath(dir);
// 在ftp上创建目录
mkDirs(dirs);
// 判断是否是目录
if (dir.isDirectory()) {
// 列举本地上传目录下的所有文件
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
uploadDirectory(files[i]);
}
} else {
// 上传该文件
upload(dir);
}
}
/**
* 获取文件保存相对路径
*
* @param file
* @return
*/
public String getSavePath(File file) {
// 如果是上传至根目录,则不创建目录
if (file.getName().equals(ROOT_PATH)) {
return null;
}
String absPath = file.getParent();
int index = absPath.indexOf(ROOT_PATH);
if (index > -1) {
return absPath.substring(index + ROOT_PATH.length());
}
return null;
}
/**
* 创建层级目录
*
* @param client
* @param path
* @throws FTPException
* @throws FTPIllegalReplyException
* @throws IOException
* @throws IllegalStateException
* @throws FTPException
* @throws FTPIllegalReplyException
* @throws IOException
* @throws IllegalStateException
*/
protected void mkDirs(String path) throws IllegalStateException,
IOException, FTPIllegalReplyException, FTPException {
if (null == path) {
return;
}
String cpath = client.currentDirectory();
client.changeDirectory("/");// 切换到根目录
StringTokenizer dirs = new StringTokenizer(path, File.separator);
String temp = null;
boolean flag = false;
while (dirs.hasMoreElements()) {
temp = dirs.nextElement().toString();
if (!isDirExist(temp)) {
client.createDirectory(temp);// 创建目录
client.changeDirectory(temp);// 进入创建的目录
flag = true;
}
}
if (flag) {
System.out.println(">>>>>create directory:[" + path + "]");
}
client.changeDirectory(cpath);
}
/**
* 上传文件到指定的目录下
*
* @param client
* 被指定上传的目录
* @param file
* 被上传的文件
* @throws IOException
* @throws FTPAbortedException
* @throws FTPDataTransferException
* @throws FTPException
* @throws FTPIllegalReplyException
* @throws IllegalStateException
*/
protected void upload(File file) throws IOException, IllegalStateException,
FTPIllegalReplyException, FTPException, FTPDataTransferException,
FTPAbortedException {
// 切换到上传目录
String sPath = getSavePath(file);
if (sPath == null) {
sPath = "/";
}
// 如果当前目录 不是上传的目的目录,则切换目录
if (!client.currentDirectory().equals(sPath)) {
client.changeDirectory(getSavePath(file));
}
// 上传到client所在的目录
client.upload(file);
System.out.println(">>>>>upload file [" + file.getAbsolutePath()
+ "] to FTP directory: [" + client.currentDirectory() + "]");
}
/**
* 检查目录是否存在
*
* @param dir
* @param ftpClient
* @return
*/
public boolean isDirExist(String dir) {
try {
client.changeDirectory(dir);
} catch (Exception e) {
return false;
}
return true;
}
/**
* 断开连接
*
* @throws FTPException
* @throws FTPIllegalReplyException
* @throws IOException
* @throws IllegalStateException
*/
public void disConnect() throws IllegalStateException, IOException,
FTPIllegalReplyException, FTPException {
client.disconnect(true);
System.out.println(">>>>>login out......");
}
}
6主运行类
package com.main;
import java.io.IOException;
import com.dbtool.TimerManager;
/**
* 启动定时任务,主程序入口
* @author whh
*
*/
public class mainApp {
public static void main(String[] args) throws IOException {
new TimerManager();
}
}