How to check if a folder exists?
To check if a folder exists in Java, you can use the java.nio.file.Files
class and its exists
method. This method returns true
if the specified path exists and false
otherwise.
Here is an example of how you can use the exists
method to check if a folder exists:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws Exception {
String dirName = "mydir";
Path dirPath = Paths.get(dirName);
if (Files.exists(dirPath)) {
System.out.println("The directory exists.");
} else {
System.out.println("The directory does not exist.");
}
}
}
This code creates a Path
object representing the directory and then checks if it exists using the exists
method.
I hope this helps! Let me know if you have any other questions.