How do I check if a directory exists in Java?

5

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

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

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

}
    
asked by anonymous 25.03.2014 / 20:10

2 answers

5

You can create Path from a String just use the methods of class 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 remember that this new API of files was added from Java 7.

  

To learn more See the following documentation:

     

Retrieved from link

     

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

    
25.03.2014 / 20:23
3

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

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

You can still test if the file is actually a directory using isDirectory() :

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

See javadoc for java.io.File .     

25.03.2014 / 20:15