Home > Net >  Skip folder if it does not exists using java
Skip folder if it does not exists using java

Time:12-06

I have created a property file in java named prop.properties inside eclipse.

In prop.properties file, I have added below lines:- users = user1,user2,user3

where user1 , user2 and user3 are folders.

I have created directory named TestDir which contains, user1,user3 folders

Suppose if user2 folder is not present in TestDir, I have to skip that and consider the other folder.

I have used the below code,

int fileCount = directory.list().length;
File[] logFiles = directory.listFiles();
            if (logFiles != null) {
                for (File f : logFiles) {
                System.out.println(f);
                }
}

But I am getting error. The error is,

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because the return value of "java.io.File.list()" is null

Can someone help with resolution

CodePudding user response:

The problem is getting the count when the directory list is null will fail on the first line. Add a test that sets fileCount to zero in that case. Like,

File[] logFiles = directory.listFiles();
int fileCount = (logFiles == null) ? 0 : logFiles.length;
for (File f : logFiles) { // <-- this is safe
    System.out.println(f);
}
  •  Tags:  
  • java
  • Related