java中遍历文件,再将txt文件聚合到一起

import java.io.*;
import java.util.ArrayList;

/**
 * 将oldPath这个目录下的所有txt文件遍历读取
 * 然后全部放到newFile这个文件里
 * 
 */
public class GetSome {
    ArrayList<String> listPath = new ArrayList<>();
    ArrayList<String> listFile = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        GetSome getSome = new GetSome();

        String oldPath = "C:\\Users\\Desktop\\agent";
        String newFile = "C:\\Users\\Desktop\\1.txt";

        //得到oldpath目录下的所有txt文件目录
        getSome.copyPath(oldPath,getSome);
        //读取所有txt文件里的内容
        getSome.readFilePath(getSome.listPath,getSome);
        //将txt文件里的内容写入newFile文件
        getSome.writeFile(getSome.listFile,newFile);
    }

    public void writeFile(ArrayList<String> list,String path) throws IOException {
        File file = new File(path);
        if (!file.exists()){
            file.createNewFile();
        }

        BufferedWriter bw = new BufferedWriter(new FileWriter(path));
        for (String str:list){
            bw.write(str + "\n");
            bw.flush();
        }
        bw.close();
    }

    public void readFilePath(ArrayList<String> listPath,GetSome getSome) throws IOException {
        for (String str:listPath){
            getSome.readfile(str,getSome);
        }
    }
	
    public void readfile(String path,GetSome getSome) throws IOException {
        if (!path.contains(".txt")){
            return;
        }
        BufferedReader br = new BufferedReader(new FileReader(path));
        String str = br.readLine();
        while (str != null){
            getSome.listFile.add(str);
            str = br.readLine();
        }
    }

	//传入目录,进行遍历
    public void copyPath(String path,GetSome getSome) {

        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
                System.out.println("文件夹是空的!");
                return;
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        copyPath(file2.getAbsolutePath(),getSome);
                    } else {
                        getSome.listPath.add(file2.getAbsolutePath());
//                        System.out.println("文件:" + file2.getAbsolutePath());
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值