Trong Java, có hai phương pháp chính để kiểm tra xem file hoặc thư mục có tồn tại hay không. Đó là:
1 - Files.exists từ package NIO
2 - File.exists từ package IO legacy
Hãy xem một số ví dụ từ mỗi package.
Kiểm Tra File Tồn Tại (Java NIO)
Code dùng Path và Paths từ package Java NIO để kiểm tra file tồn tại:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CheckFileExist {
public static void main(String[] args) {
Path path = Paths.get("/path/to/file/app.log");
if (Files.exists(path)) {
if (Files.isRegularFile(path)) {
System.out.println("App log file exists");
}
} else {
System.out.println("App log file does not exists");
}
}
}
Kiểm Tra Thư Mục Tồn Tại (Java NIO)
Tương tự, nếu chúng ta muốn kiểm tra thư mục tồn tại trong Java dùng package NIO:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CheckDirectoryExist {
public static void main(String[] args) {
Path path = Paths.get("/path/to/logs/");
if (Files.exists(path)) {
if (Files.isDirectory(path)) {
System.out.println("Logs directory exists");
}
} else {
System.out.println("Logs directory does not exist");
}
}
}
Kiểm Tra File Tồn Tại (Java Legacy IO)
Nếu bạn không dùng package Java NIO, bạn có thể dùng package Java IO legacy:
import java.io.File;
public class CheckFileExists {
public static void main(String[] args) {
File file = new File("/path/to/file/app.log");
if(file.exists()) {
System.out.println("App log file exists");
} else {
System.out.println("App log file does not exist");
}
}
}
Kiểm Tra Thư Mục Tồn Tại (Java Legacy IO)
Tương tự, để kiểm tra thư mục chúng ta có thể dùng:
import java.io.File;
public class CheckFileExists {
public static void main(String[] args) {
File file = new File("/path/to/logs/");
if(file.isDirectory()) {
System.out.println("Logs directory exists");
} else {
System.out.println("Logs directory does not exist");
}
}
}