如何检查一个文件夹是否存在?

我正在尝试一些新的Java 7 IO特性。实际上,我正在尝试检索文件夹中的所有XML文件。但是,当文件夹不存在时,会抛出异常。如何使用新的IO检查文件夹是否存在?

public UpdateHandler(String release) {
log.info("searching for configuration files in folder " + release);
Path releaseFolder = Paths.get(release);
try(DirectoryStream<Path> stream = Files.newDirectoryStream(releaseFolder, "*.xml")){
    

for (Path entry: stream){
log.info("working on file " + entry.getFileName());
}
}
catch (IOException e){
log.error("error while retrieving update configuration files " + e.getMessage());
}
}
435678 次浏览

很简单:

new File("/Path/To/File/or/Directory").exists();

如果你想确定它是一个目录:

File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
...
}

你需要将你的Path转换为File并测试是否存在:

for(Path entry: stream){
if(entry.toFile().exists()){
log.info("working on file " + entry.getFileName());
}
}

使用java.nio.file.Files:

Path path = ...;


if (Files.exists(path)) {
// ...
}

你可以选择传递这个方法LinkOption值:

if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {

还有一个方法notExists:

if (Files.notExists(path)) {
File sourceLoc=new File("/a/b/c/folderName");
boolean isFolderExisted=false;
sourceLoc.exists()==true?sourceLoc.isDirectory()==true?isFolderExisted=true:isFolderExisted=false:isFolderExisted=false;

不需要单独调用exists()方法,因为isDirectory()隐式检查目录是否存在。

使用实例检查新IO目录是否存在。

if (Files.isDirectory(Paths.get("directory"))) {
...
}

如果文件是目录,isDirectory返回true;false如果文件不存在,不是目录,或者无法确定该文件是否是目录。

看到:文档

从文件夹目录的字符串生成一个文件

String path="Folder directory";
File file = new File(path);

和use method存在 如果你想要生成文件夹,你可以使用mkdir()

if (!file.exists()) {
System.out.print("No Folder");
file.mkdir();
System.out.print("Folder created");
}

我们可以检查文件和文件夹。

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
}
}
}
import java.io.File;
import java.nio.file.Paths;


public class Test
{


public static void main(String[] args)
{


File file = new File("C:\\Temp");
System.out.println("File Folder Exist" + isFileDirectoryExists(file));
System.out.println("Directory Exists" + isDirectoryExists("C:\\Temp"));


}


public static boolean isFileDirectoryExists(File file)


{
if (file.exists())
{
return true;
}
return false;
}


public static boolean isDirectoryExists(String directoryPath)


{
if (!Paths.get(directoryPath).toFile().isDirectory())
{
return false;
}
return true;
}


}

SonarLint,如果你已经有了路径,使用path.toFile().exists()代替Files.exists以获得更好的性能。

Files.exists方法在JDK 8中的性能明显较差,当用于检查实际上不存在的文件时,会显著降低应用程序的速度。< br > < br > Files.notExistsFiles.isDirectoryFiles.isRegularFile也是如此

不合规代码示例:

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

兼容的解决方案:

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