1.数据库备份的类
package com.dbtool;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
public class DataBaseTool{
static String sqlurl = GetProperties.getSqlurl();
static String path = GetProperties.getPath();
static String sqlNum = null;
public DataBaseTool() throws IOException {
backup();
}
public static void backup() {
try {
Runtime rt = Runtime.getRuntime();
Process child = rt.exec(sqlurl);
InputStream in = child.getInputStream();
InputStreamReader xx = new InputStreamReader(in, "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();
Date date = new Date();
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
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;
public class OperationTimer extends TimerTask{
public void run() {
try {
new DataBaseTool();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(60*1000);
new ftpUtil("ip", "21", "用户名", "密码", new File("D://任务//"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
3.定时启动任务
package com.dbtool;
import java.io.*;
import java.util.*;
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]);
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 = new Properties();
InputStream in = GetProperties.class.getClassLoader().getResourceAsStream("backup.properties");
try {
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
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
sqlurl = C:/Program Files (x86)/MySQL/MySQL Server 5.5/bin/mysqldump -uroot -p123 mydb tb_item
path = D:/LeaveDatabase/tb-.sql
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
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = D:
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
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =D:
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";
String host=null;
String port=null;
String username=null;
String password=null;
File dir=null;
public ftpUtil() throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, 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();
}
}
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;
}
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() + "]");
}
public void uploadDirectory(File dir) throws IOException,
IllegalStateException, FTPIllegalReplyException, FTPException,
FTPDataTransferException, FTPAbortedException {
if (!dir.exists()) {
return;
}
String dirs = getSavePath(dir);
mkDirs(dirs);
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
uploadDirectory(files[i]);
}
} else {
upload(dir);
}
}
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;
}
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);
}
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.upload(file);
System.out.println(">>>>>upload file [" + file.getAbsolutePath()
+ "] to FTP directory: [" + client.currentDirectory() + "]");
}
public boolean isDirExist(String dir) {
try {
client.changeDirectory(dir);
} catch (Exception e) {
return false;
}
return true;
}
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;
public class mainApp {
public static void main(String[] args) throws IOException {
new TimerManager();
}
}