使用案例: 需要以事务方式将文件从一个位置移动到另一个位置。如果操作失败,则必须回滚相应的操作。
我选择了 Apache Commons Transaction 库。
我尝试使用 FileResourceManager 中的 moveResource 函数,下面是我的代码。
代码:
public static void moveFiles() throws ResourceManagerException {
FileResourceManager fileResourceManager=null;
String txId = null;
try {
String workDir = "D:\\source";
String storeDir = "D:\\destination";
fileResourceManager = new FileResourceManager(storeDir, workDir, false, LOGGER_FACADE,true);
fileResourceManager.start();
txId = fileResourceManager.generatedUniqueTxId();
fileResourceManager.startTransaction(txId);
fileResourceManager.moveResource(txId,workDir,storeDir,true);
fileResourceManager.commitTransaction(txId);
//if any exception arises rollback
} catch (ResourceManagerException resourceManagerException) {
fileResourceManager.rollbackTransaction(txId);
resourceManagerException.printStackTrace();
}
}
Is it a right way to move files ? , below is my source directory (where file present) and destination directory (where file needs to be moved)
[![source and destination directories][1]][1]
[1]: https://i.stack.imgur.com/oS6x5.png
要以事务方式实现此操作,您可以复制整个文件,然后从源位置删除。如果我们直接尝试移动文件,则在失败的情况下其内容可能会损坏,因此回滚将无济于事。
public static void moveFiles() throws Exception {
Path source = Paths.get("C:\\sourced\\A.txt");
Path destination = Paths.get("C:\\destination",source.getFileName().toString());
Path fileToBeDeleted = source;
try {
Files.createFile(destination);
Files.copy(source, destination, StandardCopyOption.COPY_ATTRIBUTES);
}catch (Exception e){
logger.log(Level.WARNING,"Error while copyingFile to destination");
fileToBeDeleted = destination;
}finally {
try {
Files.deleteIfExists(fileToBeDeleted);
}catch (Exception e){
logger.log(Level.SEVERE,"File not deleted from source/destination");
throw new IllegalStateException("Error while deleting file in source/destination "+fileToBeDeleted);
}
}
}
上述实现是使用
java.nio
包完成的。您可以使用 apache 实用程序进行文件操作 ApacheFileUtil