📄 backupimpl.java
字号:
package com.briup.inf.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
import java.util.Collection;
import java.util.Properties;
import com.briup.exception.BackupException;
import com.briup.inf.Backup;
import com.briup.inf.Config;
import com.briup.inf.Gather;
/**
* class BackupImpl
*
* @author Jimmy Zhou
* @Date 2008-2-4 下午11:24:34
*/
public class BackupImpl implements Backup {
private String bak_file_path;
public BackupImpl(Properties pro) {
bak_file_path = pro.getProperty("bak_file_path");
createFile();
}
/**
* 清除备份文件内容
*/
public void clear() throws BackupException {
try {
RandomAccessFile raf = new RandomAccessFile(bak_file_path, "rw");
raf.setLength(0);
raf.close();
} catch (Exception e) {
e.printStackTrace();
throw new BackupException(e);
}
}
/**
* 导入备份数据文件内容,返回一个collection
*/
public Collection load() throws BackupException {
Collection c = null;
ObjectInputStream ois = null;
File file = new File(bak_file_path);
if (file.length() < 1) {
clear();
}
if (file.length() > 1) {
try {
FileInputStream fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
Object obj = ois.readObject();
if (obj != null) {
c = (Collection) obj;
}
} catch (Exception e) {
e.printStackTrace();
throw new BackupException(e);
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return c;
}
/**
* 当网络出现异常或想数据库插入记录时出现异常,将所有数据记录备份存储到备份文件中。
*/
public void store(Collection c) throws BackupException {
File file = new File(bak_file_path);
ObjectOutputStream oos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
oos.writeObject(c);
oos.flush();
} catch (Exception e) {
e.printStackTrace();
throw new BackupException(e);
} finally {
try {
if (oos != null) {
oos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void createFile() {
File file = new File(bak_file_path);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] agrs) {
Properties pro = new Properties();
pro.setProperty("config_file_path", "src/com/briup/config.xml");
Config config = ConfigImpl.newInstance(pro);
try {
Backup bu = config.getBackup();
Gather gather = config.getGather();
Collection c1 = gather.doGather();
System.out.println(c1.size());
bu.store(c1);
c1 = bu.load();
System.out.println(c1.size());
bu.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -