java多個文件合并為一個文件
package com.vfsd.core; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; public class MergeOnePersonDataAndWriteFile { public static void main(String[] args) { List<String> listFiles = new ArrayList<String>(); String filePath1="G:\\matlab心電\\心電數(shù)據(jù)按工人分類2\\工人5(26下午)\\2020-12-26-14-51-04_1.txt"; String filePath2="G:\\matlab心電\\心電數(shù)據(jù)按工人分類2\\工人5(26下午)\\2020-12-26-16-43-15_1.txt"; String filePath3="G:\\matlab心電\\心電數(shù)據(jù)按工人分類2\\工人5(26下午)\\2020-12-26-15-44-57_1.txt"; String filePath4="G:\\matlab心電\\心電數(shù)據(jù)按工人分類2\\工人5(26下午)\\2020-12-26-16-35-23_1.txt"; String filePath5="G:\\matlab心電\\心電數(shù)據(jù)按工人分類2\\工人5(26下午)\\2020-12-17-14-27-36_1.txt"; listFiles.add(filePath1); listFiles.add(filePath2); listFiles.add(filePath3); listFiles.add(filePath4); listFiles.add(filePath5); String outputFile = "G:\\matlab心電\\心電數(shù)據(jù)按工人分類5\\工人5(26下午)\\2020-12-26.txt"; try { readAndWriteFileData(listFiles, outputFile); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void readAndWriteFileData(List<String> listFiles,String outputFilePath) throws Exception{ File outputFile = new File(outputFilePath); File outputFileParentFolder = new File(outputFile.getParent()); if(!outputFileParentFolder.exists()) { outputFileParentFolder.mkdirs(); } FileWriter fileWriterObj = new FileWriter(outputFile); BufferedWriter bufferedWriterObj = new BufferedWriter(fileWriterObj); for(int k=0;k<listFiles.size();k++) { String indexFilePath = listFiles.get(k); System.out.println(indexFilePath); File oldFile = new File(indexFilePath); FileReader fileReaderObj = new FileReader(oldFile); BufferedReader bufferedReaderObj = new BufferedReader(fileReaderObj); String lineStr=""; while((lineStr=bufferedReaderObj.readLine())!=null) { if(lineStr !="") { bufferedWriterObj.write(lineStr+"\n"); } } bufferedWriterObj.flush(); bufferedReaderObj.close(); fileReaderObj.close(); } bufferedWriterObj.flush(); bufferedWriterObj.close(); fileWriterObj.close(); } }
|
|