在项目中需要批量导入文件夹及子文件夹,子文件,这样就可以通过递归的方式去操作,但是在我们的数据库中还要子文件夹个数,子文件个数,文件夹大小这三个字段,这样我们就需要通过数据库根据当前文件夹的id一层层去遍历它所有的子文件夹并统计然后在反写入,这样我们就可以通过递归的方式去实现。
package com.zzg.file.batchupload;
import java.util.List;
import java.util.Set;
import com.zzg.core.AbstractCurdManager;
import com.zzg.core.web.listener.StaticLoad;
import com.zzg.file.directory.Directory;
import com.zzg.file.file.File;
public class DirInfo {
private static AbstractCurdManager curdManager = (AbstractCurdManager) StaticLoad
.getBean("curdManager");
static class CountVO {
private long dircount; // 子文件夹个数
private long filecount; // 子文件个数
private long size; // 所有子文件的大小和
public CountVO() {
this.dircount = 0;
this.filecount = 0;
this.size = 0;
}
public CountVO(long dircount, long filecount, long size) {
this.dircount = dircount;
this.filecount = filecount;
this.size = size;
}
public CountVO Sigma(CountVO vo) {
return new CountVO(vo.dircount + this.dircount, vo.filecount
+ this.filecount, vo.size + this.size);
}
}
/**
* 根据父文件夹获得该文件夹的所有子文夹件个数,所有子文件个数以及所有子文件的大小的和 并且循环更新各级父文件夹的信息
*
* @return
*/
public static void updateDirInfo(Directory directory) {
CountVO vo = reCountDirInfo(directory);
Directory ele = directory;
while (ele.getDirectory() != null
&& (ele = (Directory) curdManager.get(Directory.class, ele
.getDirectory().getId())) != null) {
ele.setChildren_folder_count(ele.getChildren_folder_count()
+ vo.dircount);
ele.setChildren_file_count(ele.getChildren_file_count()
+ vo.filecount);
ele.setCurrentSize(ele.getCurrentSize() + vo.size);
curdManager.save(ele);
}
}
/**
* 根据父文件夹获得该文件夹的所有子文夹件个数,所有子文件个数以及所有子文件的大小的和
*
* @return
*/
@SuppressWarnings("unchecked")
public static CountVO reCountDirInfo(Directory directory) {
// 得到所有的子文件夹
List<Directory> childrenList = curdManager.getObjs("from com.unis.file.directory.Directory dir where dir.directory.id='" + directory.getId() + "'");
// 得到当前文件夹下的子文件夹的个数
CountVO total = new CountVO(childrenList.size(), 0, 0);
// 加上子文件的数据
total = total.Sigma(getChildrenFile(directory));
// 循环所有的子文件夹
for (Directory child : childrenList) {
//reCountDirInfo递归,当没有子文件夹时开始返回
total = total.Sigma(reCountDirInfo(child));
}
// 把当前文件夹的大小更新到数据库
directory.setChildren_folder_count(total.dircount);
directory.setChildren_file_count(total.filecount);
directory.setCurrentSize(total.size);
curdManager.save(directory);
return total;
}
/**
* 根据父文件夹得到子文件的个数和子文件的大小(一级子目录)
*
* @return
*/
@SuppressWarnings("unchecked")
private static CountVO getChildrenFile(Directory directory) {
CountVO total = new CountVO();
//total.filecount = directory.getChildren_file_count();
List<File> childrenFileList = curdManager
.getObjs("from com.unis.file.file.File f where f.directory ='"
+ directory.getId() + "'");
for (File child : childrenFileList) {
total.size += child.getSize();
}
total.filecount = childrenFileList.size();
return total;
}
}