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

来源:互联网 发布:卷积神经网络算法代码 编辑:程序博客网 时间:2024/06/05 07:30
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();
}
}
}
}
}
原创粉丝点击