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();
			}
		}
	}
}


發佈了30 篇原創文章 · 獲贊 7 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章