【发布时间】:2017-10-24 10:38:49
【问题描述】:
我需要根据各自的部分合并两个具有相似标题但数据不同的 CSV 文件中的数据。 CSV 文件将包含两部分,第一部分包含根据部门的数据,第二部分包含来自住宅区的数据。这是我的第一个 CSV 文件
Sector,Total Number of Occurrence
sector1,12
sector2,30
sector3,100
House,Total Number of Occurrence
B12,80
A2,87
我的第二个 CSV 文件
Sector,Total Number of Occurrence
sector 99,89
sector 11,9
House,Total Number of Occurrence
Q11,22
Q22,67
我希望生成一个包含两个数据的 CSV 文件,但数据必须分配到正确的部分,如下所示
Sector,Total Number of Occurrence
sector1,12
sector2,30
sector3,100
sector 99,89
sector 11,9
House,Total Number of Occurrence
B12,80
A2,87
Q11,22
Q22,67
但我想我目前开发的源代码无法做到这一点,因为它包含 CSV 中列出的第二个标头 House,Total Number of Occurrence。我可以知道如何实现我想要的输出吗?这就是我当前的 csv 输出的样子
Sector,Total Number of Occurrence
sector1,12
sector2,30
sector3,100
House,Total Number of Occurrence
B12,80
A2,87
sector 99,89
sector 11,9
House,Total Number of Occurrence
B12,80
A2,87
这是我目前开发的源代码
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SummarizeReport1
{
static ArrayList<String> list1 = new ArrayList<>();
static String line1;
public static void main(String[] args) throws IOException
{
List<Path> paths = Arrays.asList(Paths.get("C:\\Users\\user\\Desktop\\file\\log\\backup\\report12017-10-31.csv"), Paths.get("C:\\Users\\user\\Desktop\\file\\log\\backup\\report12017-10-31 - Copy.csv"));
List<String> mergedLines = getMergedLines(paths);
Path target = Paths.get("C:\\Users\\user\\Desktop\\file\\log\\backup\\SummarizedReport1.csv");
Files.write(target, mergedLines, Charset.forName("UTF-8"));
}
private static List<String> getMergedLines(List<Path> paths) throws IOException
{
List<String> mergedLines = new ArrayList<> ();
for (Path p : paths)
{
List<String> 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;
}
}
【问题讨论】: