简体   繁体   中英

Java: for-loop can only execute once

I have two class fiels, one is named CSVUtils.java and the other one is named FilesCollector.java. The CSVUtils.java contains a static method named matchValues(String csvFile, int columnNumber, String matchValue) that is called by the FilesCollector.java. Basically it is like this

Public Class CSVUtils {

    private static String FILENAME;
    private static int COLUMN;
    private static String MATCHVALUE;
  public static void matchValues(String csvFile, int columnNumber, String matchValue) {
    try {  
     //read csvFile, match values, and write to outPut file. details omitted.
   } finally {
        csvReader.close();
        csvWriter.close();
        System.out.println("success");
        System.exit(0); 
    }

  }
}

In FilesCollector.java, I use the Apache Commons-IO to fetch a list of CSV files and store it in an array File[] csvFiles. I then use the below for-loop to process individual csv file

for (File e : csvFiles) {
  CSVUtils.matchValues(e.getAbsolutePath(), 9, "Yes");
}

However, for some reason I don't know, this above for-loop can only process the first csv file in File[] csvFiles array. Can you guys help me where might be wrong in my code? Thanks a lot!

edit: after commenting out this line System.exit(0); my code is working. Why this line of code made the method not work?

In your finally block you call System.exit(0) , so after you process one file you shutdown your program.

Hence whatever the length of csvFiles is, you'll process only the first file.

finally {
        csvReader.close();
        csvWriter.close();
        System.out.println("success");
        System.exit(0); <--- here
    }

Remove this line and you'll be fine.

You are shutting down the program with

System.exit(0); 

so it doesn't continue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM