java实现读取txt文件和将内容写入txt文件

1.java读取txt和写入txt文件

package com.ztesoft.TestClusterHHHT;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;

import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class TestCreate {

	public static void main(String[] args) throws IOException {

		Map rowDataMap = readTxtFile("E:\\createTable\\mcc_sub_extend_001.txt");
		Map provinceMap = readTxtFile("E:\\createTable\\province.txt");

		List textList = new ArrayList(10000);

		Iterator iterator = rowDataMap.keySet().iterator();
		while (iterator.hasNext()) {
			Integer key = iterator.next();
			String rowdata = rowDataMap.get(key);
			String province = provinceMap.get(key);
			// 对文件进行行合并
			textList.add(province + "," + rowdata);
		}

		// 将内容写入文件
		writeTxtFile("E:\\createTable\\merge.txt", textList);

	}

	/**
	 * 根据文件路径读取文件
	 * 
	 * @param filePath
	 *            文件路径
	 * @return Map
	 */
	private static Map readTxtFile(String filePath) {

		Map textMap = new HashMap(10000);

		try (FileInputStream fileInputStream = new FileInputStream(filePath);
				InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
				BufferedReader bufferedReader = new BufferedReader(inputStreamReader);) {

			String line = null;
			Integer i = 0;
			while ((line = bufferedReader.readLine()) != null) {
				i = i + 1;
				textMap.put(i, line);
			}

		} catch (Exception e) {
			e.printStackTrace();

		}

		return textMap;
	}

	/**
	 * 写入文件
	 * 
	 * @param filePath
	 *            文件路径
	 * @param textList
	 *            文件行内容
	 * @throws IOException
	 *             异常信息
	 */
	private static void writeTxtFile(String filePath, List textList) throws IOException {

		File file = new File(filePath);
		file.createNewFile();

		try (FileWriter fileWriter = new FileWriter(file);
				BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);) {

			for (String text : textList) {
				bufferedWriter.write(text);
	            bufferedWriter.newLine();
			}

			bufferedWriter.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

你可能感兴趣的:(javaSE基础,java-ee)