问题描述
这应该工作。它检查要合并的文件是否具有匹配的头。否则将引发异常。异常处理(关闭流等)已作为练习。
String[] headers = null;
String firstFile = "/path/to/firstFile.dat";
Scanner scanner = new Scanner(new File(firstFile));
if (scanner.hasNextLine())
headers[] = scanner.nextLine().split(",");
scanner.close();
Iterator<File> iterFiles = listOfFilesToBeMerged.iterator();
BufferedWriter writer = new BufferedWriter(new FileWriter(firstFile, true));
while (iterFiles.hasNext()) {
File nextFile = iterFiles.next();
BufferedReader reader = new BufferedReader(new FileReader(nextFile));
String line = null;
String[] firstLine = null;
if ((line = reader.readLine()) != null)
firstLine = line.split(",");
if (!Arrays.equals (headers, firstLine))
throw new FileMergeException("Header mis-match between CSV files: '" +
firstFile + "' and '" + nextFile.getAbsolutePath());
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
reader.close();
}
writer.close();
解决方法
我有一些具有相同列标题的CSV文件。例如
文件A
header1,header2,header3
one,two,three
four,five,six
文件B
header1,header3
seven,eight,nine
ten,eleven,twelve
我想将其合并,以便将数据合并到一个文件中,文件头位于顶部,但其他任何地方都没有文件头。
header1,six
seven,twelve
什么是实现此目标的好方法?