How to check if a directory exists in Java?

Asked

Viewed 3,548 times

5

I’m trying to check if a directory typed in JTextField exists or not. I tried to use Files.notExists() but the first argument must be of the type Path and I couldn’t figure out how to convert from String.

String caminho = txtDirIndexado.getText().replace("\\", "\\\\");

 if (Files.notExists(caminho, LinkOption.NOFOLLOW_LINKS)) {

}

2 answers

5


You can create Path from a String just use the class methods Paths (plural), for example:

Path p1 = Paths.get("/tmp/foo");
Path p2 = Paths.get(args[0]);
Path p3 = Paths.get(URI.create("file:///Users/joe/FileTest.java"));

Just don’t forget that this new API files added from Java 7.

For more information see the following documentation:

Taken from http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

The class Path includes various methods that can be used to get information about a path, access elements of a path, convert a path into other forms, or stray portions of a path. There are also methods to search for paths and methods to remove redundancies.

3

A directory can be represented by java.io.File, which has a method exists(). You can create an object File, and call the exists() in the form:

File file = new File(caminho);
if (file.exists()) {
    // fazer algo se diretorio existe
}

You can still test whether the file is really a directory using isDirectory():

if (file.exists()) {
    if (file.isDirectory()) {
        String[] conteudo = file.list();
    ...
...
}

See the javadoc for java.io.File.

  • I’m getting the following message in Eclipse: Multiple markers at this line - path cannot be resolved to a variable - The method exists(Path, Linkoption...) in the type Files is not applicable for the Arguments (File, Linkoption)

  • @Strokes, caminho, in the answer above is a variable. You need to initialize it to use. An example: String caminho = "C:\UmDiretorio";. Change your code and try again.

  • Yes, I know that. I adapted it for my code but it keeps giving this error. The @Leonardo Otto example worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.