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,
To check if a directory exists with the new IO:
if (Files.isDirectory(Paths.get("directory"))) {
...
}
isDirectory
returns true
if the file is a directory; false
if the file does not exist, is not a directory, or it cannot be determined if the file is a directory or not.
See: documentation.
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 forFiles.notExists
,Files.isDirectory
andFiles.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
}
We can check files and thire Folders.
import java.io.*;
public class fileCheck
{
public static void main(String arg[])
{
File f = new File("C:/AMD");
if (f.exists() && f.isDirectory()) {
System.out.println("Exists");
//if the file is present then it will show the msg
}
else{
System.out.println("NOT Exists");
//if the file is Not present then it will show the msg
}
}
}
Using java.nio.file.Files
:
Path path = ...;
if (Files.exists(path)) {
// ...
}
You can optionally pass this method LinkOption
values:
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
There's also a method notExists
:
if (Files.notExists(path)) {