返学费网 > 培训机构 > 成都斯芬克

18581508556

全国统一学习专线 8:30-21:00

 编写一个程序,将一个目录及其子目录下的所有txt类型的文本文件中的内容和并到若干个新文件中,当第一个新产生的文件中存储的内容达到1M bytes时,剩下的内容存储到第二个文件中,依次往下,新产生的文本文件名依次为 1.txt, 2.txt.......


gzpoplar(poplar) 的程序比较正确,但缺少过滤txt文件的功能
hdhmail2000(禅剑飞雪)的程序中,不能正确分割文件大小,我用每个文件1k来测试,结果有的文件竟然是2.2k,不过我也没看出程序中错误的地方
下面是本人对gzpoplar(poplar) 程序的改进:
package csdn.example;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;


public class File_csdn1 {
String srcdir = %26#34;src%26#34;;
String descdir = %26#34;desc%26#34;;

File srcfile = null;
FileInputStream fis = null;
FileOutputStream fos = null;
int descfilenum = 1;
long size = 0;
final long MaxSize = 1024*1024;//1M

public File_csdn1() {
}

public File_csdn1(String src, String desc) {
srcdir = src;
descdir = desc;
}

public void go() throws Exception {
srcfile = new File(srcdir);
if ((!srcfile.exists()) || (!srcfile.isDirectory())) {
throw new Exception(%26#34;/%26#34;%26#34; + srcdir + %26#34;/%26#34; dir does not exist!%26#34;);
}

File descfile = new File(descdir);
if ((!descfile.exists()) || (!srcfile.isDirectory())) {
descfile.mkdir();
}
fos = new FileOutputStream(descdir + %26#34;/%26#34; + descfilenum + %26#34;.txt%26#34;);
nest(srcdir);
fos.close();
}

public void nest(String dir) throws Exception {
srcfile = new File(dir);
String[] files = srcfile.list();

boolean havesubdir = false;
//处理文件
for (int i=0; i
srcfile = new File(dir + %26#34;/%26#34; + files[i]);
if (srcfile.isDirectory()) {
havesubdir = true;
continue;
}
else {
if(srcfile.getName().lastIndexOf(%26#34;.txt%26#34;)>=0){//过滤txt文件
fis = new FileInputStream(srcfile);
//System.out.println(srcfile.getPath());
int n;
byte[] buf = new byte[4096];
while ((n = fis.read(buf, 0, buf.length)) != -1) {
write(buf, n);
}
}
else
continue;
}
}
//没有子目录,返回
if (!havesubdir) {
return;
}
//处理文件夹
for (int i=0; i
srcfile = new File(dir + %26#34;/%26#34; + files[i]);
if (srcfile.isFile()) {
continue;
}
nest(srcfile.getPath());
}
}

public void write(byte[] buffer, int end) throws Exception {
int p = 0;
while (p < end) {
if (size >= MaxSize) {
descfilenum++;
size = 0;
fos.close();
fos = new FileOutputStream(descdir + %26#34;/%26#34; + descfilenum + %26#34;.txt%26#34;);
}
int len = end - p;
if ((size+len) > MaxSize) {
int m = (int)(MaxSize - size);
fos.write(buffer, p, m);
p += m;
size += m;
}
else {
fos.write(buffer, p, end-p);
size += (end - p);
p = end;
}
}
}


public static void main(String[] args) {
try {
File_csdn1 f = new File_csdn1(%26#34;/root/temp%26#34;, %26#34;/root/temp1%26#34;);
f.go();
} catch (Exception e) {
e.printStackTrace();
}
}

}

温馨提示:为不影响您的学业,来校区前请先电话咨询,方便我校安排相关的专业老师为您解答
  • 详情请进入成都斯芬克
  • 已关注:419
  • 咨询电话:
  • 热门课程
姓名不能为空
手机号格式错误