将CSV文件合并到一个没有重复标题的文件中 [英] Merge CSV files into a single file with no repeated headers

查看:158
本文介绍了将CSV文件合并到一个没有重复标题的文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些CSV文件具有相同的列标题。例如

I have some CSV files with the same column headers. For example

文件A

header1,header2,header3
one,two,three
four,five,six

档案B

header1,header2,header3
seven,eight,nine
ten,eleven,twelve

我想合并它,以便数据合并到一个文件,头顶部,但没有其他头。

I want to merge it so that the data is merged into one file with the headers at the top, but no headers anywhere else.

header1,header2,header3
one,two,three
four,five,six
seven,eight,nine
ten,eleven,twelve

实现这个?

推荐答案

这应该可以工作。它检查正在合并的文件是否具有匹配的标头。否则会抛出异常。异常处理(关闭流等)已作为练习留下。

This should work. It checks if the file being merged have matching headers. Would throw an exception otherwise. Exception handling (to close the streams etc.) has been left as an exercise.

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文件合并到一个没有重复标题的文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆