Calling getParent()
on a Path
object can result in a potential NullPointerException
. I am not sure if SonarQube could do something about this, but I share it here. Maybe it give you some idea how you can implement or extend a rule.
Example Java Code:
Path file = /* some value */;
Files.createDirectories(file.getParent());
… is creating following NPE:
java.lang.NullPointerException
at java.nio.file.Files.provider(Files.java:97)
at java.nio.file.Files.createDirectory(Files.java:674)
at java.nio.file.Files.createAndCheckIsDirectory(Files.java:781)
at java.nio.file.Files.createDirectories(Files.java:727)
Because file.getParent() returns null when the path is not absolute (and is a single path-segment). To be more concrete:
-
file = Paths.get("out/file.txt")
will work -
file = Paths.get("/tmp/file.txt")
will work -
file = Paths.get("file.txt")
does not work and creates the NullPointerException
My fix is:
Files.createDirectories(file.toAbsolutePath().getParent());