最近业务上需求,两个文本的内容需要逐行对应的进行拼接。因为数据比较大,所以手动是不可能的,写了个小程序,顺便做做笔记。
先看看效果。
首先需要读取两文本之中的内容。
/*
*读取文本1的方法,将读取到的数据存入HashMap里面后续方便提取
*读取文本2也是这个方法,需要修改下文本2的读取路径
*/
public static HashMap<Integer, String> readFile1() {
HashMap<Integer, String> map = new HashMap<Integer,String>();
//当前文本放的位置,根据需求自己修改
String path = "C:/Users/xx/Desktop/1.txt"; try { FileInputStream in = new FileInputStream(path); InputStreamReader inReader = new InputStreamReader(in, "UTF-8"); BufferedReader bufReader = new BufferedReader(inReader); String line = null; int i = 0; while ((line = bufReader.readLine()) != null) { System.out.println("我是文本1======>"+line); for (; i < 5;) { map.put(i, line); i++; break; } } } catch (FileNotFoundException e) { System.out.println("文件没有找到"); e.printStackTrace(); } catch (UnsupportedEncodingException e) { System.out.println("无法转义"); e.printStackTrace(); } catch (IOException e) { System.out.println("文件读取失败"); e.printStackTrace(); } return map; }
写入文本3的方法。
/*
* 写入文本方法
* 参数a-文本1读取的内容;参数b-文本2读取的内容;price是要求添加的参数
*/
public static void writeFile(String a, String b, int price) { String path = "C:/Users/xx/Desktop/3.txt"; String slo = a+","+b+","+price+"|"; System.out.println("存入的数据" + slo); File filename = new File(path); try { FileWriter out = new FileWriter(filename, true); BufferedWriter write = new BufferedWriter(out); out.write(slo); write.newLine(); out.flush(); out.close(); } catch (IOException e) { System.out.println("文件写入失败"); e.printStackTrace(); } }
//方法结束
主方法。
/*
*2019.12.6 新增 xy
*拼接文本的主方法
*/
public static void main(String[] args) { HashMap<Integer, String> map1 = readFile1(); HashMap<Integer, String> map2 = readFile2(); String a = ""; String b = ""; for (int i = 0; i < 5; i++) { a = map1.get(i); b = map2.get(i); writeFile(a, b, 30); } }
如果需要之后,需要逐行写入,那么只要在需要写入的数据后面添加 "\r\n"
String slo = a + "\r\n";
到这里,基本的要求算是实现了,但是还有一些地方具有局限性。
新人,写的不好的地方,希望各位大牛给点意见或建议,万分感谢!
原文:https://www.cnblogs.com/xuyang94/p/11994632.html