Comprobar si una ruta representa un archivo o una carpeta


Necesito un método válido para comprobar si un String representa una ruta para un archivo o un directorio. ¿Qué son los nombres de directorio válidos en Android? A medida que sale, los nombres de las carpetas pueden contener caracteres '.', entonces, ¿cómo entiende el sistema si hay un archivo o una carpeta? Gracias de antemano.

Author: Jim G., 2012-10-08

7 answers

Suponiendo que path es su String.

File file = new File(path);

boolean exists =      file.exists();      // Check if the file exists
boolean isDirectory = file.isDirectory(); // Check if it's a directory
boolean isFile =      file.isFile();      // Check if it's a regular file

Véase File Javadoc


O puedes usar la clase NIO Files y comprobar cosas como esta:

Path file = new File(path).toPath();

boolean exists =      Files.exists(file);        // Check if the file exists
boolean isDirectory = Files.isDirectory(file);   // Check if it's a directory
boolean isFile =      Files.isRegularFile(file); // Check if it's a regular file
 145
Author: Baz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-13 09:09:14

Solución limpia mientras se mantiene con la API de nio:

Files.isDirectory(path)
Files.isRegularFile(path)
 34
Author: pgsandstrom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-16 12:51:30

Por favor, se adhieren a la API de nio para realizar estas comprobaciones

import java.nio.file.*;

static Boolean isDir(Path path) {
  if (path == null || !Files.exists(path)) return false;
  else return Files.isDirectory(path);
}
 19
Author: Sheng,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-23 14:28:54
String path = "Your_Path";
File f = new File(path);

if (f.isDirectory()){



  }else if(f.isFile()){



  }
 4
Author: Kumar Vivek Mitra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-08 11:11:35

Para comprobar si una cadena representa una ruta de acceso o un archivo de forma programática, debe usar métodos API como isFile(), isDirectory().

¿Cómo entiende el sistema si hay un archivo o una carpeta?

Supongo que las entradas de archivos y carpetas se mantienen en una estructura de datos y es administrada por el sistema de archivos.

 2
Author: Juvanis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-08 11:09:58

No hay forma de que el sistema le diga si String representa a file o directory, si no existe en el sistema de archivos. Por ejemplo:

Path path = Paths.get("/some/path/to/dir");
System.out.println(Files.isDirectory(path)); // return false
System.out.println(Files.isRegularFile(path)); // return false

Y para el siguiente ejemplo:

Path path = Paths.get("/some/path/to/dir/file.txt");
System.out.println(Files.isDirectory(path));  //return false
System.out.println(Files.isRegularFile(path));  // return false

Así que vemos que en ambos casos el sistema devuelve false. Esto es cierto tanto para java.io.File como para java.nio.file.Path

 1
Author: Emdadul Sawon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-25 10:10:12
   private static boolean isValidFolderPath(String path) {
    File file = new File(path);
    if (!file.exists()) {
      return file.mkdirs();
    }
    return true;
  }
 0
Author: Kaweesi Joseph,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-17 15:13:58