在图片的存储中,一个文件夹保存的数量不能过多。到达一定数量后需要另起文件进行处理。如有三层文件夹深度,每个文件夹只允许放置2048个子文件夹及文件。现算法实现如下
public static boolean judgeFolderFileOverNumber(String path) {
boolean flag = false;
try {
File f = new File(path);
if (f.isDirectory()) {
if (f.listFiles().length > Constant.PIC_NUMBER_LIMIT)
flag = true;
}
} catch (Exception e) {
}
return flag;
}
public static String getFolderPath(String path, int level, boolean rtv) {
// 0 1. upload/,0,false ==> 2. upload/1/,1,false,==> 3. upload/1/1/,2,false==>4 upload/1/1/1/,3,false
if (level <= 3) {
try {
File f = new File(path);
if (!f.exists())
f.mkdirs();
if (judgeFolderFileOverNumber(path) && !rtv && (level==3 )) {
rtv = true;
path = getFolderPath(path, level, rtv);//如果是叶子才可以往回处理
} else {
if (rtv){//处理判断已满的情况,路径后退一级 upload/1/1/1/=> upload/1/1/
level = level - 1;
int end = path.lastIndexOf(File.separator) - 1;
path = path.substring(0, end);
end = path.lastIndexOf(File.separator) + 1;
path = path.substring(0, end);
if ( judgeFolderFileOverNumber( path ) ){
path = getFolderPath(path, level, rtv);
} else {
File f2 = new File(path);
int fs = f2.listFiles().length;
if (fs ==0 )
fs = 1;
else
fs = fs + 1;//对当前文件夹判断,不大于2048则切换文件夹
if (path.substring(path.length() - 1, path.length()).equals(File.separator))
path = path + "" + fs + File.separator ;
else
path = path + File.separator + "" + fs + File.separator ;
level= level + 1;
if ( level <=3 ) {
rtv = false;
path = getFolderPath(path, level, rtv);
}
}
} else {
int fs = f.listFiles().length;
if (fs ==0 )
fs = 1;
if ( level <3 ){
if (path.substring(path.length() - 1, path.length()).equals(File.separator))
path = path + "" + fs + File.separator ;
else
path = path + File.separator + "" + fs + File.separator ;
level = level + 1;
path = getFolderPath(path, level, rtv);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return path;
}