Java对多个合并的快速处理

/**文件类,记录文件的各个属性*/

public class TxtFile {
	public static void main(String[] args) {
		TxtFile txtFile = new TxtFile("E:/Test.txt");
		System.out.println(txtFile.readFile());
	}

	private String filePath;

	public TxtFile(String filePath) {
		this.filePath = filePath;
	}

	public StringBuffer readFile() {
		return readFile(null);
	}

	public StringBuffer readFile(Object condition) {
		File file = new File(filePath);
		BufferedReader reader = null;
		StringBuffer result = new StringBuffer();
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			double tempHeight = 0.0;
			while ((tempString = reader.readLine()) != null) {

				// 对每一行进行处理
				result.append(tempString + "\r\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	public static void deleteFile(String path) {
		File file = new File(path);
		file.delete();
	}
}

 

/** 合并多个文件 */

public class CompileFiles {

	private String fileCatalog;
	private String resultPath;

	public static void main(String[] args) {
		String fileCatalog = "E:/";// 文件目录
		String resultPath = "E:/test.txt";
		CompileFiles cf = new CompileFiles(fileCatalog, resultPath);
		cf.compileTxtFiles();
	}

	public CompileFiles(String fileCatalog, String resultPath) {
		this.fileCatalog = fileCatalog;
		this.resultPath = resultPath;
	}

	/** 合并多个文件 */
	public void compileTxtFiles() {
		TxtFile.deleteFile(resultPath);// 清空结果文件

		File file = new File(fileCatalog);
		String[] paths = file.list();
		ArrayList<String> txtList = new ArrayList<String>();

		for (String path : paths) {
			if (path.endsWith(".txt")) {
				txtList.add(file.getAbsolutePath() + path);
			}
		}
		compileTxtFiles(txtList, resultPath);
	}

	private void compileTxtFiles(List<String> filePathsList, String resultPath) {
		PrintWriter out = null;
		try {
			out = new PrintWriter(new BufferedWriter(new FileWriter(resultPath,
					true)));
			List<TxtFile> fileList = new ArrayList<TxtFile>();
			Map<TxtFile, Double> fileListMap = new HashMap<TxtFile, Double>();
			Map<TxtFile, StringBuffer> fileContentMap = new HashMap<TxtFile, StringBuffer>();

			while (fileListMap.size() > 0) {
				for (int i = 0; i < fileList.size(); i++) {
					TxtFile file = fileList.get(i);

					// 处理每个文件的内容即可
					out.print(file.readFile());

					if (fileListMap.get(file) != null) {
						fileListMap.remove(file);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值