java 文件存储路径_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());

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值