How to check if a folder exists

后端 未结 10 1879
滥情空心
滥情空心 2020-11-28 21:21

I am playing a bit with the new Java 7 IO features, actually I trying to receive all the xml files of a folder. But this throws an exception when the folder does not exist,

10条回答
  •  野性不改
    2020-11-28 22:04

    From SonarLint, if you already have the path, use path.toFile().exists() instead of Files.exists for better performance.

    The Files.exists method has noticeably poor performance in JDK 8, and can slow an application significantly when used to check files that don't actually exist.

    The same goes for Files.notExists, Files.isDirectory and Files.isRegularFile.

    Noncompliant Code Example:

    Path myPath;
    if(java.nio.Files.exists(myPath)) {  // Noncompliant
        // do something
    }
    

    Compliant Solution:

    Path myPath;
    if(myPath.toFile().exists())) {
        // do something
    }
    

提交回复
热议问题