2016-01-28 16 views
0

在我的程序中,我可以读取一个csv文件。逐行解析信息到一个方法。但如果csv没有通过if检查,我不想调用“otherMethod(id,new);”在所有。因此,在调用其他方法之前,整个CSV必须通过。在缓冲区中读取csv,检查它是否通过检查 - >将信息逐行转发到方法

所以我的问题是:我怎样才能在某种缓冲区中读取整个csv,检查它是否通过了if检查并在之后处理它(逐行)?

boolean csvPassed = true; 
int index = 0; 
double id = Double.NaN, new = Double.NaN; 

while ((String line = reader.readLine()) != null) { 
    Scanner scanner = new Scanner(line); 
    scanner.useDelimiter(";"); 
    while (scanner.hasNext()) { 
     //check the csv line by line 
     if (index == 0) 
      id = Integer.parseInt(data); 
     else if (index == 1) { 
      new = Integer.parseInt(data); 
      if (new == 10) 
        csvPassed = false 
     } 
     //whatever you want to do here 
    } 
} 

//after the file is checked 
if(csvPassed){ 
    // If the csv passes the check, call the method line by line... 
    otherMethod(id, new); 
} 
+0

如果csv不是很大,可以将所有数字读入一个'ArrayList'。如果它很大,那么你需要通过csv两次。请注意,只要您看到值为10,就可以停止处理额外的行。最后,名为'new'的变量需要重命名。 –

+0

我的答案是否能解决您的问题?如果是这样,那么如果你接受它会很好,如果不是,那么请留下评论,说明你的问题。 – sebhaub

回答

3

这可能对你有帮助。

BufferedReader reader = new BufferedReader(new FileReader("<YOUR_FILENAME>")); 
//your buffer to store the lines of your csv 
List<Integer[]> lines = new LinkedList<>(); 
//a flag to indicate the success 
boolean passed = true; 
//read in the file line by line 
String currentLine; 
while((currentLine = reader.readLine()) != null){ 
    //split the line up at your delimiter 
    String[] lineSplit = currentLine.split(";"); 
    //the array to store the parsed integers of the current line 
    Integer[] parsedLine = new Integer[lineSplit.length]; 

    //process each element of that line and check for your condition 
    for(int i = 0; i < lineSplit.length; i++){ 
     //make sure you can parse that string 
     parsedLine[i] = Integer.parseInt(lineSplit[i]); 
     if(parsedLine[i] == 10){ 
      //Maybe you could also exit your loop here and clear the list? 
      passed = false; 
     } 
    } 
    //add this line to your buffer 
    lines.add(parsedLine); 
} 

//If all lines passed the condition, process line by line out of your buffer 
if(passed){ 
    //make sure you have the 2 values in the array 
    for(Integer[] line : lines){ 
     otherMethod(line[0], line[1]); 
    } 
} 
+0

他想读取某种缓冲区中的while文件,并且如果所有行都通过检查而不包含“10”,那么他想要逐行调用另一个方法? – sebhaub

相关问题