フォルダーが存在するかどうかを確認する方法


199

新しい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());
    }


}

2
フォルダが存在するかどうかを確認する必要があるのはなぜですか。チェックしたときにフォルダが存在するからといってDirectoryStream、を作成したときにフォルダが存在するという意味ではなく、フォルダエントリを反復処理するときに言うまでもありません。
Oswald

回答:


262

使用java.nio.file.Files

Path path = ...;

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

オプションで、このメソッドのLinkOption値を渡すことができます。

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

メソッドもありますnotExists

if (Files.notExists(path)) {

30
また、両方のことをノートFiles.exists(path)とはFiles.notExists(path)同時にfalseを返すことができます!これは、パスが実際に存在するかどうかをJavaが判別できなかったことを意味します。
Sanchit 2013年

O_O @Sanchitそれを言うための強い議論はありますか?
Richard

6
ドキュメントはそう言っています。:) link notExistsメソッドが実際に適切にリンクできないことを確認します。
Sanchit 2014年

13
Files.isDirectory(Path、LinkOption);
Kanagavelu Sugumar 2014年

2
@LoMaPh !Files.exists(path)Files.notExists(path)100%同じではありません。Javaがファイルが存在するかどうかを判別できない場合は、最初のコードが返さtrueれ、2番目のコードが返されfalseます。
Jesper、

205

非常にシンプル:

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

そして、あなたが確実にしたいのであれば、それはディレクトリです:

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

40
正解ですが、少し注意:if(f.isDirectory()) {...}存在も確認するので十分です。
G. Demecki

3
これはOPの質問には答えません。java.io.fileOPが参照する「新しいJava 7 IO機能」の一部ではありません。java.nio.fileJavaの7で導入されたパッケージは、提供していますPathsし、Filesクラスを。ここでの他の回答は、これらの新しいクラスを使用してOPの問題を解決する方法を正しく説明しています。
Doron Gold

53

新しいIOのディレクトリが存在するかどうかを確認するには:

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

isDirectorytrueファイルがディレクトリかどうかを返します。falseファイルが存在しない、ディレクトリでない、またはファイルがディレクトリであるかどうかを判別できない場合。

参照:ドキュメント


6

パスをに変換してFile、存在をテストする必要があります。

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

5

フォルダディレクトリの文字列からファイルを生成します

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

と使用方法が存在します。
フォルダーを生成する場合は、mkdir()を使用する必要があります

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

4

ディレクトリが存在するかどうかexists()isDirectory()暗黙的にチェックするため、メソッドを個別に呼び出す必要はありません。


4
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;
  }

}

1
File sourceLoc=new File("/a/b/c/folderName");
boolean isFolderExisted=false;
sourceLoc.exists()==true?sourceLoc.isDirectory()==true?isFolderExisted=true:isFolderExisted=false:isFolderExisted=false;

sourceLoc.isDirectory()はブール結果を返します。"sourceLoc.isDirectory()== true"を使用する必要はありません
Oleg Ushakov

1

ファイルとフォルダをチェックできます。

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      
        }
    }
}

ネットワーク共有ファイルでは機能しないようです。キャッチ:org.codehaus.groovy.runtime.typehandling.GroovyCastException:オブジェクト 'Z:\\ tierWe bServices \ Deploy \ new.txt'をクラス 'org.codehaus.groovy.runtime.GStringImpl'でクラス 'java.nio'にキャストできません.fi le.Path 'org.codehaus.groovy.runtime.typehandling.GroovyCastException:クラス' org.codehaus.groovy.runtime.GStringImpl 'のオブジェクト' Z:\\ tierWebService s \ Deploy \ new.txt 'をクラスにキャストできません'java.nio.file.Path'
Jirong Hu

0

SonarLintから、すでにパスがある場合は、path.toFile().exists()代わりにFiles.existsをしてパフォーマンスを向上させます。

このFiles.exists方法は、JDK 8では著しくパフォーマンスが低下し、実際には存在しないファイルをチェックするために使用すると、アプリケーションを大幅に遅くする可能性があります。

同じことがのために行くFiles.notExistsFiles.isDirectoryFiles.isRegularFile

違反コード:

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

準拠ソリューション:

Path myPath;
if(myPath.toFile().exists())) {
    // do something
}
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.