《黑马程序员》高级io作业第一题

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

 

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * 
 * 类说明:此类遍历一个目录下的所有txt文件,并将其中所有的内容拷贝到一个新的txt文件中
 * 作者:test
 * 版本:v1.0 
 * 修改历史:
 */
public class Test1 {
 
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Test1().transformTxt(new File("e://test1"));
}
 
// 转化一个目录下的所有txt文件到一个新的txt文件中
public void transformTxt(File file) {
File[] fileArray = file.listFiles();
for (File f : fileArray) {
if (f.isFile()
&& f.getName()
.substring(f.getName().lastIndexOf(".") + 1,
f.getName().length())
.equalsIgnoreCase("txt")) {
writeFiletoNew(f);
} else if (f.isDirectory()) {
transformTxt(f);
} else {
}
}
}
 
private File ff;
private int i = 1;
private long total = 0;
 
public void writeFiletoNew(File f) {
FileInputStream fin = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
try {
fin = new FileInputStream(f);
bis = new BufferedInputStream(fin);
byte[] b = new byte[1024];
int len = 0;
while ((len = bis.read(b)) != -1) {
total += len;
ff = new File(i + ".txt");
if (total >= 1024 * 1024) {
ff = new File((++i) + ".txt");
}
fos = new FileOutputStream(ff, true);
fos.write(b, 0, len);
fos.flush();
}
 
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
bis.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
 
}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值