2017-10-18 64 views
1

我消耗由外部过程中产生的CSV。该CSV会出现在不同的地方,需要包含或排除不同的列。环路CSV的每一行,并删除直到第N逗号在Java中

在文件中的差异的例子...

文件1:

Col1,Col2,Col3,Col4,Col5 
ABC,DEF,GHI,JKL,MNO 

文件2:

Col4,Col5 
JKL,MNO 

伪:

1. Open the initial CSV file and create a new CSV file. 
2. Loop through the CSV file and for each line copy the columns needed 
3. Drop new file in new location 

我卡住复制正确的列或只是rem在他们身上。有没有简单的方法来循环每一行,只是删除数据到某个逗号?

+2

欢迎堆栈溢出!你有没有试过编码?你是否按姓名或号码包含或排除列?你是在列的文本字段中处理逗号,还是仅仅祈祷永远不会存在? – AJNeufeld

+0

如果您使用Java8或较新的起飞看看https://stackoverflow.com/questions/769621/dealing-with-commas-in-a-csv-file?rq=1 – reporter

+0

@AJNeufeld谢谢!是的,文件复制和重写不是问题。我能删除第一标题行(按名称,恩。Col1中,col2的,COL3),但由于之后的每一行不遵循相同的格式(更动态的数据,可以是ABC,XYX,烧烤),我不能不要用同样的逻辑去除那些。 生成CSV的外部过程不允许在文本字段中使用逗号,所以我不必担心这一点。 – seesharp

回答

0

斯普利特CSV用逗号,把你需要的列。 在这个演示中,我只显示了一行CSV,但是你可以扩展这个程序来处理多行。

import java.util.*; 
import java.lang.*; 
import java.io.*; 

{ 
    public static void main (String[] args) throws java.lang.Exception 
    { 
     // Read a file into inputCsv 
     String inputCsv = "c0,c1,c2,c3"; 
     String outputCsv = ""; 
     int[] colsNeeded = {1,3}; 

     String[] cols = inputCsv.split(","); 
     for(int i = 0; i < colsNeeded.length; i++){ 
      outputCsv += cols[colsNeeded[i]]; 
      if(i < colsNeeded.length - 1) 
       outputCsv += ","; 
     } 
     System.out.println(outputCsv); 
     // Write output Csv onto some file 
    } 
} 
+1

请注意,不断添加到字符串很慢,您可能想直接写入文件(使用BufferedWriter帮助)。在一气呵成的完整文件读取也似乎有点过分取决于文件大小,它可能更容易对线路基础 – phflack

+0

线处理这些就是我感觉懒得实现很好的建议:P 一个更更好的解决方案是完全消除文件写入。 OP说数据来自另一个过程。管理数据而不是通过磁盘I/O会更合理。 –

0

只需使用univocity-parsers为:

String input = "Col1,Col2,Col3,Col4,Col5\n" + 
      "ABC,DEF,GHI,JKL,MNO\n"; 

    Reader inputReader = new StringReader(input); //reading from your input string. Use FileReader for files 
    Writer outputWriter = new StringWriter(); //writing into another string. Use FileWriter for files. 

    CsvParserSettings parserSettings = new CsvParserSettings(); //configure the parser 
    parserSettings.selectFields("Col4", "Col5"); //select fields you need here 

    //For convenience, just use ready to use routines. 
    CsvRoutines routines = new CsvRoutines(parserSettings); 

    //call parse and write to read the selected columns and write them to the output 
    routines.parseAndWrite(inputReader, outputWriter); 

    //print the result 
    System.out.println(outputWriter); 

输出:

Col4,Col5 
    JKL,MNO 

希望这有助于。

声明:我是该库的作者。它是开放源代码和免费的(Apache 2.0许可证)。