需要做一个简单的定期数据备份,开始想到是 quatz ,查了些资料发现 quatz 功能比较强大,而自己的需求很简单,能定期备份数据就行。
查到了util.timer何timertask两个类,可以定期执行任务。而数据备份做一个读取文件和文件夹的就可以。如下:
1.数据备份
1
package copy;
2
3
import java.io.*;
4
5
public class CopyDirectory
{
6
// 源文件夹
7
static String url1 = "test";
8
// 目标文件夹
9
static String url2 = "F:/mirc1/";
10
11
12
public static void copy ()throws IOException
{
13
14
(new File(url2)).mkdirs();
15
File[] file = (new File(url1)).listFiles();
16
for (int i = 0; i < file.length; i++)
{
17
if (file[i].isFile())
{
18
copyFile(file[i], new File(url2 + file[i].getName()));
19
}
20
if (file[i].isDirectory())
{
21
String sourceDir = url1 + File.separator + file[i].getName();
22
String targetDir = url2 + File.separator + file[i].getName();
23
copyDirectiory(sourceDir, targetDir);
24
}
25
}
26
}
27
28
public static void copyFile(File sourceFile, File targetFile)
29
throws IOException
{
30
FileInputStream input = new FileInputStream(sourceFile);
31
BufferedInputStream inBuff = new BufferedInputStream(input);
32
33
FileOutputStream output = new FileOutputStream(targetFile);
34
BufferedOutputStream outBuff = new BufferedOutputStream(output);
35
36
byte[] b = new byte[1024 * 5];
37
int len;
38
while ((len = inBuff.read(b)) != -1)
{
39
outBuff.write(b, 0, len);
40
}
41
outBuff.flush();
42
43
inBuff.close();
44
outBuff.close();
45
output.close();
46
input.close();
47
}
48
49
public static void copyDirectiory(String sourceDir, String targetDir)
50
throws IOException
{
51
(new File(targetDir)).mkdirs();
52
File[] file = (new File(sourceDir)).listFiles();
53
for (int i = 0; i < file.length; i++)
{
54
if (file[i].isFile())
{
55
File sourceFile = file[i];
56
File targetFile = new File(new File(targetDir)
57
.getAbsolutePath()
58
+ File.separator + file[i].getName());
59
copyFile(sourceFile, targetFile);
60
}
61
if (file[i].isDirectory())
{
62
String dir1 = sourceDir + "/" + file[i].getName();
63
String dir2 = targetDir + "/" + file[i].getName();
64
copyDirectiory(dir1, dir2);
65
}
66
}
67
}
68
}
69
2 . 设定数据备份工作执行时间间隔
1
package copy;
2
3
import java.util.Date;
4
import java.util.Timer;
5
6
public class CopyWork
{
7
public static void main(String[] args)
{
8
Date date = new Date();
9
Timer timer = new Timer();
10
timer.schedule(new Worker(), new Date(), 60000);
11
}
12
13
}
14
3.测试
1
package copy;
2
3
import java.io.IOException;
4
import java.util.TimerTask;
5
6
public class Worker extends TimerTask
{
7
8
@Override
9
public void run()
{
10
try
{
11
CopyDirectory.copy();
12
} catch (IOException e)
{
13
14
e.printStackTrace();
15
}
16
17
}
18
19
}
20