如何从csv文件中删除垃圾值?

时间:2015-02-08 17:28:09

标签: java eclipse csv

我有一个包含一些数据的CSV文件,但它中还包含大量无效数据。如何仅打印有效数据并留下其余数据?

我的数据是这样的: -

1,Ron,1234,XYZ
2,Harry,214,SDA
3,Kent,1786,GHI
SAMNE:MANNS;ndndo
kdbg;obmgdf;brhj 

我想只打印前3行并删除最后两行无效行。我在Eclipse中这样做。

3 个答案:

答案 0 :(得分:2)

你可以尝试这样的事情。

    BufferedReader reader = new BufferedReader(new FileReader(new File("~/input.csv")));
    String line;
    while((line = reader.readLine())!= null){
        try{

            int sno = Integer.parseInt( line.split(",")[0]);
            System.out.println("Valid "+ line);
            //Continue doing more checks or other operations 

        }catch(NumberFormatException e){
            //Skip invalid line  
            System.out.println("Invalid row "+ line);
        }
    }

答案 1 :(得分:0)

你应该用正则表达式检查是否有效,抛出异常是个坏主意。

BufferedReader reader = new BufferedReader(new FileReader(new File("~/input.csv")));
String line;
while((line = reader.readLine())!= null){
    if(line.matches("(\\d+,\\w+,\\d+,\\w+)"){
       print line;
    }
 }

答案 2 :(得分:0)

这样的事情:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class JavaApplication1 {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
            StringBuilder sb = new StringBuilder();
            String line = reader.readLine();
            while (line != null) {
                String[] part = line.split(",");
                try {
                    Integer.parseInt(part[0]);
                    System.out.println(line);
                } catch (NumberFormatException nfe) {
                    // This is not a valid line
                }
                line = reader.readLine();
            }
        }
    }
}