Java 合并两个具有不同头的csv文件
我需要合并两个CSV文件中的数据与类似的头,但不同的数据根据各自的部分。CSV文件将包含两个部分,第一部分包含根据部门的数据,第二部分包含来自住宅区的数据。这是我的第一个CSV文件 我的第二个CSV文件Java 合并两个具有不同头的csv文件,java,csv,Java,Csv,我需要合并两个CSV文件中的数据与类似的头,但不同的数据根据各自的部分。CSV文件将包含两个部分,第一部分包含根据部门的数据,第二部分包含来自住宅区的数据。这是我的第一个CSV文件 我的第二个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
sector 99,89
sector 11,9
House,Total Number of Occurrence
Q11,22
Q22,67
我希望生成的CSV文件中包含这两个数据,但必须将数据分配到如下所示的正确部分
但我想我目前开发的源代码无法做到这一点,因为它包含CSV中列出的第二个标题,即House,总发生次数。我可以知道如何达到我想要的产出吗?这就是我当前的csv输出
这是我目前开发的源代码
首先,创建一个类来存储标题和每一行
public class SubFile{
private String headers;
private List<String> lines
}
每次在第一行或空行之后读取标头时,都需要检查该标头是否与集合中的实例匹配,以继续添加到集合中,或创建实例
public SubFile getInstance(String headerLine){
/*
instance = search instance in collection
if (instance not found)
create instance
add it to the list
return instance
*/
}
我相信这很容易实现,所以我让您先试试,您有算法要使用。谢谢您的建议,您的意思是我需要在另一个程序中创建另一个类调用子文件,并将CSV头存储在子文件中声明的列表中吗?我不是这方面的专家java@yumi我会使用另一个类来保持代码的干净性和可读性,但是如果你不能使用一个类,那么你总是可以不用它,你可以简单地使用两个列表,一个列表标题,阅读列表行就不那么有趣了。两个列表的长度相同,标题的索引将与其行的索引匹配。就像我说的,不再干净;当然,学习OOP和如何在Java中使用简单类并不需要太多,这里不需要继承,所以您只需要基础知识。
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;
}
}
public class SubFile{
private String headers;
private List<String> lines
}
List<SubFile> files;
public SubFile getInstance(String headerLine){
/*
instance = search instance in collection
if (instance not found)
create instance
add it to the list
return instance
*/
}