路径"/>
java 文件存储路径
抛砖引玉吧 应该可以解决你的需求,不过有一个问题是 如果中间某个文件或文件夹被删除 则无法自动补充 求解答package cn.istudy.util;
import java.io.File;
import java.io.IOException;
public class FileTest {
public static final int CHILD_LIMIT = 10;// 最大啊子文件数
public static final int DEEP_LIMIT = 7;// 文件夹深度
public static void main(String[] args) {
FileTest ft = new FileTest();
File root = new File("d:\\testfile\\");
try {
for (int i = 0; i < 45; i++) {
System.out.println(i + "--->" + ft.testFile(root, 0, false));
}
} catch (IOException e) {
e.printStackTrace();
}
// ft.delFile(root);
}
public boolean testFile(File root, int k, boolean nextChild)
throws IOException {
int i = 0;// 文件名 个位数
int j = 0;// 文件名 十位数
System.out.println("i--->" + i + " j--->" + j
+ " k--->" + k);
if (root.exists() && root.isDirectory() && root.canRead()
&& root.canWrite()) {
File[] children = root.listFiles();
File child = null;
if (children.length == 0) {// 如果子目录数为0
child = new File(root, j + "" + i);// 创建新文件对象
if (k == DEEP_LIMIT) {// 如果深度已达限制则创建文件
child.createNewFile();
return true;
} else {// 否则为目录 并深度递增
child.mkdir();
k++;
nextChild = false;
return testFile(child, k, nextChild);// 递归
}
} else if (children.length > 0 && children.length < CHILD_LIMIT) {// 如果有子目录且数量未达到子目录限制
if (k == DEEP_LIMIT) {// 如果深度已达限制 则创建文件
i = children.length % 10;
j = children.length / 10;
child = new File(root, j + "" + i);// 文件名以当前目录子文件数+1
child.createNewFile();
return true;// 返回
} else {// 否则 则进入目录
if (nextChild) {// 如果标识为下一个子目录 则文件名为当前子目录数+1
i = children.length % 10;
j = children.length / 10;
} else {// 否则 为当前子目录最后一个目录
i = (children.length - 1) % 10;
j = (children.length - 1) / 10;
}
child = new File(root, j + "" + i);
k++;// 深度递增
if (!child.exists()) {// 如果子目录不存在 则创建目录
child.mkdir();
nextChild = false;// 并标识进入当前目录
}
}
return testFile(child, k, nextChild);// 递归
} else if (children.length >= CHILD_LIMIT) {// 如果子目录数已达限制
nextChild = true;// 标识进入下一个子目录
return testFile(root.getParentFile(), --k, nextChild);// 递归
}
} else {
throw new IOException();
}
return false;
}
public void delFile(File root) {
File[] children = root.listFiles();
if (children.length > 0) {
for (int i = 0; i < children.length; i++) {
File child = children[i];
delFile(child);
}
} else {
System.out.println(root.delete());
delFile(root.getParentFile());
}
}
}
更多推荐
java 文件存储路径
发布评论