代码段将CSV文件拆分为多个CSV文件,并将第一列内容写入子CSV文件。我在此代码中观察到的是列标题“UNIQUE ID”仅出现在FIRST CSV文件中。以下CSV文件仅包含没有标题的数据。为了获得我想到的所有文件的头文件使用ArrayList,以便我可以将头文件放在ArrayList的第一个索引和之后的其余数据。但我悲惨地失败了。
我需要有关如何修改代码的建议或帮助,以便所有子文件都应该有一个额外的UNIQUE IDENTIFIER行作为第一行的列数据。我正在粘贴我尝试过但不起作用的代码。 Child csv should look like this This is what I am getting
public static void myFunction(int lines, int files) throws FileNotFoundException, IOException {
String inputfile = "C:/Users/Downloads/CONSOLIDATED.csv";
BufferedReader br = new BufferedReader(new FileReader(inputfile));
String strLine = null;
for (int i = 1; i <= files; i++) {
FileWriter fstream1 = new FileWriter("C:/Users/Downloads/FileNumber_" + i + ".csv");
BufferedWriter out = new BufferedWriter(fstream1);
for (int j = 0; j < lines; j++) {
strLine = br.readLine();
if (strLine != null) {
String strar[] = strLine.split(",");
ArrayList<String> al=new ArrayList<String>();
al.add(0,"Unique Identifier");
al.add(1,strar[0]);
char c[] = al.toString().toCharArray();
out.write(c);
out.newLine();
}
}
out.close();
}
br.close();
}
答案 0 :(得分:0)
您的问题是您没有将标题排除在循环之外。尝试在主循环之前读取第一行的内容并将标题存储在List中。然后,每次创建新文件时,在开始内循环之前,在每个文件的第一行写入标题。
public static void myFunction(int lines, int files) throws FileNotFoundException, IOException {
String inputfile = "C:/Users/Downloads/CONSOLIDATED.csv";
BufferedReader br = new BufferedReader(new FileReader(inputfile));
String strLine = br.readLine(); //here you have the headers
String[] headers=strLine.split(",");
for (int i = 1; i <= files; i++) {
FileWriter fstream1 = new FileWriter("C:/Users/Downloads/FileNumber_" + i + ".csv");
BufferedWriter out = new BufferedWriter(fstream1);
out.write(headers[0]);
for (int j = 0; j < lines; j++) {
out.newLine();
strLine = br.readLine();
if (strLine != null) {
String strar[] = strLine.split(",");
out.write(strar[0]);
}
}
out.close();
}
br.close();
}