感谢viperasi (初级程序员)上次关于创建7层文件路径,每层最大5个子文件问题的解答,以下是他给出的程序,在他给出程序的基础上,作了小小的修改,写入数据到子文件中。现在我想可以实现追加写入数据的功能,也就是说在生成一个子文件00后,可以追加数据到00文件中,直到00文件大小10mb后,再创建01文件,而不是每次都创建新的文件,如下图~~~
需要大家的指点,多谢~~~
[code="java"]
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class FileTest {
static File root=new File("D://testfile");
public static final int CHILD_LIMIT = 5;// 最大啊子文件数
public static final int DEEP_LIMIT = 7;// 文件夹深度
public static void main(String[] args) {
String file = "d://Java08IO.ppt";
InputStream input = new FileInputStream(file);
testFile(input, root, 0, false);
}
public static boolean testFile(InputStream in, File root, int k, boolean nextChild)
throws IOException {
int i = 0;// 文件名 个位数
int j = 0;// 文件名 十位数
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) {// 如果深度已达限制则创建文件
BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(child,true));
byte[] buffer = new byte[1024];
int len;
int off = 0;
while ( (len = in.read(buffer, off, 1024)) != -1) {
out.write(buffer, off, len);
}
out.flush();
return true;
} else {// 否则为目录 并深度递增
child.mkdir();
k++;
nextChild = false;
return testFile(in, 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
BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(child,true));
byte[] buffer = new byte[1024];
int len;
int off = 0;
while ( (len = in.read(buffer, off, 1024)) != -1) {
out.write(buffer, off, len);
}
out.flush();
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(in, child, k, nextChild);// 递归
} else if (children.length >= CHILD_LIMIT) {// 如果子目录数已达限制
nextChild = true;// 标识进入下一个子目录
return testFile(in, root.getParentFile(), --k, nextChild);// 递归
}
} else {
throw new IOException();
}
return false;
}
}
[/code]
[img]http://dl.iteye.com/upload/attachment/193116/3b713de8-860f-31bb-b267-7d112b885b64.jpg[/img]