我有一个带有列的CSV文件,该列跨越多行。我想将这些多行聚合成一行。
例如
1, "asdsdsdsds", "John"
2, "dfdhifdkinf
dfjdfgkdnjgknkdjgndkng
dkfdkjfnjdnf", "Roy"
3, "dfjfdkgjfgn", "Rahul"
我希望我的输出
1, "asdsdsdsds", "John"
2, "dfdhifdkinf dfjdfgkdnjgknkdjgndkng dkfdkjfnjdnf", "Roy"
3, "dfjfdkgjfgn", "Rahul"
我应该如何通过java删除新行。
答案 0 :(得分:0)
您可以使用OpenCSV创建CSV阅读器,如下所示:
CSVReader csvReader = new CSVReader(new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileName)))));
您可以使用csvReader.readNext()方法读取每一行。它返回一个String数组。
String [] nextRow = csvReader.readNext();
它将处理列中的新行。
答案 1 :(得分:0)
您应该从文件中删除行尾字符\n
,然后将文件写入csv文件。
public static void remove(String[] args) throws Exception {
CSVReader main = new CSVReader(new FileReader("path to csv file"));
String [][] look= new String [row][col];
int line =0;
String [] nextLine;
while ((nextLine = main.readNext())!=null){
nextLine[1]=nextLine[1].replaceAll("\n", "");
look[line]=nextLine;
line++;
}
BufferedWriter br = new BufferedWriter(new FileWriter("myfile.csv"));
StringBuilder sb = new StringBuilder();
for (int m=0;m<row;m++) {
for(int p=0; p<col;p++){
sb.append(look[m][p]).append(",");
}
sb.deleteCharAt(sb.lastIndexOf(","));
sb.append("\n");
}
br.write(sb.toString());
br.close();
}