使用java IO实现指定后缀的文件合并为一个文件

public class Combine {

private static final String FILE_SUFFIX = ".txt";//要合并的文件的后缀
private static final String COMBINE_FILE_PATH = "/file"; //要合并的文件所在的src路径
private static final String COMBINE_FILE_NAME = "combine" + FILE_SUFFIX;//合并后的文件的名称

public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
try {
/*
* 取出所有要合并的文件
*/
String _file_dir_path = Combine.class.getResource(COMBINE_FILE_PATH).getPath();
File _dist_file = new File(_file_dir_path + File.separator + COMBINE_FILE_NAME); //目标文件
File _file_dir = new File(_file_dir_path);
File[] _fArr  = _file_dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
if(name.endsWith(FILE_SUFFIX)){
return true;
}
return false;
}
});


if(!_dist_file.exists()){
_dist_file.createNewFile();
}


ByteArrayOutputStream baos = new ByteArrayOutputStream();
if(_fArr != null && _fArr.length > 0 ){
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(_dist_file),"utf-8"));
for (File f : _fArr) {
br = new BufferedReader(new InputStreamReader(new FileInputStream(f),"utf-8"));
String _line;
while((_line = br.readLine())!=null){
baos.write(_line.getBytes());
baos.write("\r\n".getBytes());
}
bw.write(baos.toString());
bw.flush();
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br != null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

if(bw != null){
try {
bw.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、付费专栏及课程。

余额充值