วิธีตรวจสอบว่ามีโฟลเดอร์อยู่หรือไม่


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)สามารถส่งคืนเท็จได้ในเวลาเดียวกัน! ซึ่งหมายความว่า Java ไม่สามารถระบุได้ว่ามีเส้นทางจริงหรือไม่
Sanchit

O_O @Sanchit คุณมีข้อโต้แย้งที่แข็งแกร่งที่จะพูดหรือไม่?
Richard

6
เอกสารกล่าวอย่างนั้น ลิงค์ :) ตรวจสอบวิธีการที่มีอยู่ไม่สามารถเชื่อมโยงได้อย่างถูกต้อง
Sanchit

13
Files.isDirectory (เส้นทาง, LinkOption);
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.fileไม่ได้เป็นส่วนหนึ่งของ "คุณสมบัติใหม่ของ Java 7 IO" ที่ OP อ้างถึง java.nio.fileแพคเกจซึ่งเป็นที่รู้จักใน Java 7 เสนอPathsและFilesการเรียน คำตอบอื่น ๆ ที่นี่อย่างถูกต้องอธิบายวิธีการใช้คลาสที่ใหม่กว่าเหล่านี้เพื่อแก้ปัญหา OPs
Doron Gold

53

ในการตรวจสอบว่ามีไดเรกทอรีอยู่ด้วย IO ใหม่:

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

isDirectoryส่งคืนtrueถ้าไฟล์เป็นไดเร็กทอรี 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: ไม่สามารถโยนวัตถุ' Z: \\ tierWebService s \ Deploy \ new.txt 'กับคลาส' org.codehaus.groovy.runtime.GStImpl 'ไปยังคลาส 'java.nio.file.Path'
Jirong Hu

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.