Merge CSV files into a single file with no repeated headers

后端 未结 5 1501
挽巷
挽巷 2020-12-30 10:39

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

File A

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

File B

5条回答
  •  自闭症患者
    2020-12-30 10:50

    Here is an example:

    public static void main(String[] args) throws IOException {
        List paths = Arrays.asList(Paths.get("c:/temp/file1.csv"), Paths.get("c:/temp/file2.csv"));
        List mergedLines = getMergedLines(paths);
        Path target = Paths.get("c:/temp/merged.csv");
        Files.write(target, mergedLines, Charset.forName("UTF-8"));
    }
    
    private static List getMergedLines(List paths) throws IOException {
        List mergedLines = new ArrayList<> ();
        for (Path p : paths){
            List lines = Files.readAllLines(p, Charset.forName("UTF-8"));
            if (!lines.isEmpty()) {
                if (mergedLines.isEmpty()) {
                    mergedLines.add(lines.get(0)); //add header only once
                }
                mergedLines.addAll(lines.subList(1, lines.size()));
            }
        }
        return mergedLines;
    }
    

提交回复
热议问题