user1253847
user1253847

Reputation: 5451

java : For loop isn't breaking after reaching a particular condition .

I am in the process of reading only latest 10 Files (by creation date ) from a folder using apache.commons jar

This is listing all the files , but i don't know why this isn't stopping even after completion of reading 10 files

This is my code , but i don't know why it is not stopping

import org.apache.commons.io.comparator.LastModifiedFileComparator;
import java.io.File;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        File dir = new File("D:\\MyFolder");
        File[] files = dir.listFiles();

        Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
        for (int i = 0; i < files.length; i++) {

             if(files.length==10)
             {
             // return;
                 break ; 
             }

            File file = files[i];
            System.out.printf(file.getName()+"\n");


        }


    }
}

Upvotes: 0

Views: 96

Answers (3)

Pau Kiat Wee
Pau Kiat Wee

Reputation: 9505

Wrong condition

for (int i = 0; i < files.length; i++) {

        File file = files[i];
        System.out.printf(file.getName()+"\n");
    }

Should be

for (int i = 0; i < files.length && i < 10; i++) {

        File file = files[i];
        System.out.printf(file.getName()+"\n");
}

Upvotes: 3

Neet
Neet

Reputation: 4047

Change

if(files.length==10)

to

if(i == 10)

You're always comparing to the length of the File array.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

The condition should be if (i == 10), because files.length does not change with each iteration of the loop. Better yet, change your code as follows:

int end = Math.min(files.length, 10);
for (int i = 0; i < end ; i++) {
    // ... your code
}

This would calculate the ending index once, and avoid recalculations in the loop.

Upvotes: 1

Related Questions