用处:就是export-db.bat,然后保存在一个xml里面,做数据备份。
适用范围:springside的dbunit
private static final int BUFF_SIZE = 16 * 1024;
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private DataSource dataSource;
/**
* 保存到Config配置的目录下面。
*
* @return 压缩文件的文件名
*/
public File doBackup() {
logger.debug("{}开始备份操作", SpringSecurityUtils.getCurrentUserName());
try {
FileUtils.forceMkdir(new File(Config.SYS_BACKUP_PATH));
} catch (IOException e) {
logger.error("创建备份目录失败", e);
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
String title = sdf.format(new Date());
File xmlFile = new File(Config.SYS_BACKUP_PATH, title + ".xml");
File zipFile = new File(Config.SYS_BACKUP_PATH, title + "-bak.zip");
//export to xml
exportDatabase(xmlFile);
//zip it
try {
zipFile(xmlFile, zipFile);
} catch (IOException e) {
logger.error("创建xml压缩文件失败:" + xmlFile.getAbsolutePath(), e);
return null;
}
//delete xml
try {
FileUtils.forceDelete(xmlFile);
} catch (IOException e) {
logger.error("删除临时xml文件失败:" + xmlFile.getAbsolutePath(), e);
return null;
}
logger.debug("{}备份操作成功:{}", SpringSecurityUtils.getCurrentUserName(), zipFile.getAbsolutePath());
return zipFile;
}
// 打包xml
private void zipFile(File xmlFile, File zipFile) throws IOException {
// 使用缓冲流,速度快
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(xmlFile), BUFF_SIZE);
byte buffer[] = new byte[BUFF_SIZE];
zos.putNextEntry(new ZipEntry(xmlFile.getName()));
int length = 0;
while ((length = bis.read(buffer)) != -1) {
zos.write(buffer, 0, length);
}
bis.close();
zos.flush();
zos.close();
}
private void exportDatabase(File xmlFile) {
Connection conn = null;
try {
conn = dataSource.getConnection();
IDatabaseConnection connection = new DatabaseConnection(conn);
exportDatabase(connection, xmlFile, true, true);
} catch (Exception e) {
logger.error("DBUnit Export XML 失败:" + xmlFile.getAbsolutePath(), e);
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
logger.error("备份后关闭数据库连接失败", e);
}
}
}
private void exportDatabase(IDatabaseConnection connection, File file, boolean streamed, boolean flat)
throws Exception {
if (streamed) {
connection.getConfig().setProperty(DatabaseConfig.PROPERTY_RESULTSET_TABLE_FACTORY,
new ForwardOnlyResultSetTableFactory());
}
IDataSet fullDataSet = connection.createDataSet();
FileOutputStream stream = new FileOutputStream(file);
if (flat)
FlatXmlDataSet.write(fullDataSet, stream);
else
//格式化后的xml
XmlDataSet.write(fullDataSet, stream);
stream.close();
}