我有一些数据的CSV文件,它也有很多无效的数据。我如何才能打印有效数据并保留其余部分?如何从csv文件中删除垃圾值?
我的数据是这样的: -
1,Ron,1234,XYZ
2,Harry,214,SDA
3,Kent,1786,GHI
SAMNE:MANNS;ndndo
kdbg;obmgdf;brhj
我只想打印头三行并删除最后两行无效。我在Eclipse中这样做。
我有一些数据的CSV文件,它也有很多无效的数据。我如何才能打印有效数据并保留其余部分?如何从csv文件中删除垃圾值?
我的数据是这样的: -
1,Ron,1234,XYZ
2,Harry,214,SDA
3,Kent,1786,GHI
SAMNE:MANNS;ndndo
kdbg;obmgdf;brhj
我只想打印头三行并删除最后两行无效。我在Eclipse中这样做。
你可以尝试这样的事情。
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);
}
}
你应该通过正则表达式检查是否有效,抛出异常是一个坏主意。
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;
}
}
事情是这样的:
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();
}
}
}
}
你如何定义一个有效行? – Keppil 2015-02-08 17:28:40
请考虑这样的有效行: - S.No,Name,Num,Company – 2015-02-08 17:29:36
有效表示以整数开头的行跟着','? – Shamik 2015-02-08 17:29:36