폴더가 있는지 확인하는 방법


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

O_O @Sanchit 당신은 그것을 말할 강력한 주장이 있습니까?
Richard

6
설명서에 나와 있습니다. :) link notExists 메소드가 제대로 링크 할 수 없는지 확인하십시오.
Sanchit

13
Files.isDirectory (경로, 링크 옵션);
Kanagavelu Sugumar

2
@LoMaPh !Files.exists(path)Files.notExists(path)100 % 같은 것은 아닙니다. Java가 파일이 존재하는지 판별 할 수 없으면 첫 번째 파일이 리턴 true되고 두 번째 파일이 리턴 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.file자바 7에 도입 된 패키지는,의 제공 PathsFiles클래스. 다른 답변은 이러한 새로운 클래스를 사용하여 OP 문제를 해결하는 방법을 올바르게 설명합니다.
Doron Gold

53

새 IO가있는 디렉토리가 있는지 확인하려면 다음을 수행하십시오.

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

isDirectorytrue파일이 디렉토리 인 경우를 리턴 합니다. false파일이 존재하지 않거나 디렉토리가 아니거나 파일이 디렉토리인지 판별 할 수 없습니다.

문서를 참조하십시오 .


6

Path를로 바꾸고 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"로
올렉 우샤 코프

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 : 클래스 'org.codehaus.groovy.runtime.GStringImpl'을 사용하여 'Z : \\ tierWe bServices \ Deploy \ new.txt'오브젝트를 '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 후

0

에서 SonarLint 이미 경로가있는 경우, 사용하는 path.toFile().exists()대신 Files.exists더 나은 성능을 위해.

Files.exists방법은 JDK 8의 성능이 현저히 떨어지며 실제로 존재하지 않는 파일을 검사하는 데 사용하면 응용 프로그램이 크게 느려질 수 있습니다.

동일은 간다 Files.notExists, Files.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.