Verificar existencia de diretorio e arquivo

13 respostas
C

Dado um string contento o diretorio e nome de um arquivo:

String path = "C:/TESTE/TEXT.txt

Como faço para verificar se o diretorio e o arquivo existem?

To usando o isFile() e isDirectory().
porem somente o diretorio ta conseguindo ser verificado.

Vlwww

13 Respostas

drsmachado

Bom, eu entendo que se um arquivo identificado pelo classe File sem acusar erro, ou é diretório (isDirectory) ou é File.

guilherme.dio

que eu me lembre existe um método que é assim:

if(file.Exists())

tem que verificar, n tenho certeza, talvez eu esteja me confundindo com C#

nel

chls:
Dado um string contento o diretorio e nome de um arquivo:

String path = "C:/TESTE/TEXT.txt

Como faço para verificar se o diretorio e o arquivo existem?

To usando o isFile() e isDirectory().
porem somente o diretorio ta conseguindo ser verificado.

Vlwww

Oi!

Procure sempre ler o Javadoc da api na qual está trabalhando, caso não a conheça. A do File.
Unindo o que você disse ao comentário do drsmachado, use a lógica mais óbvia.

isDirectory() é true? Então é um diretório, caso contrário, obviamente é um arquivo, certo meu camarada? :slight_smile:
Abraços.

drsmachado

Ah, e sim, é possível verificar se ele existe com o método exists(), porém, se você passar como argumento um caminho para um arquivo ou diretório inexistente, ele lança a exception null pointer.

dougfane

Excessão essa que você pode tratar com

try{ }catch(){ }

e no fim cobrir todas as possibilidades ‘-’

C

Excessão essa que você pode tratar com

try{ }catch(){ }

e no fim cobrir todas as possibilidades ‘-’

Como eu lanco a excessao se ele nao for diretorio ou arquivo…??

public class FilenameDemo {
  public static void main(String[] args) throws IOException {
    final String FPATH = "c:/test/rob.txt";
    Filename myHomePage = new Filename(FPATH, '/', '.');
    File f = new File(myHomePage.path());
    
    try{
        f.isDirectory();
            System.out.println("Path = " + myHomePage.path());
            System.out.println("DIRETORIO VALIDO");
        
    }
    catch(Exception e){
        System.err.println(e);
    }
    f = new File(FPATH);
    try{
        if(f.isFile()){
            System.out.println("Filename = " + myHomePage.filename());
            System.out.println("Arquivo VALIDO");
        }
    }
    catch(Exception e){
        System.err.println(e);
    }
    try{
        if(f.canRead())
            System.out.println("pode ler");
      }
    catch(Exception e){
        System.err.println(e);
    }
    try{
        if (f.exists())
            System.out.println("Arquivo Existe");
    }
    catch(Exception e){
        System.err.println(e);
    }
  }
}   
  
/**
 * This class assumes that the string used to initialize fullPath has a
 * directory path, filename, and extension. The methods won't work if it
 * doesn't.
 */
class Filename {
  private String fullPath;
  private char pathSeparator, extensionSeparator;

  public Filename(String str, char sep, char ext) {
    fullPath = str;
    pathSeparator = sep;
    extensionSeparator = ext;
  }

  public String extension() {
    int dot = fullPath.lastIndexOf(extensionSeparator);
    return fullPath.substring(dot + 1);
  }

  public String filename() { // gets filename without extension
    int dot = fullPath.lastIndexOf(extensionSeparator);
    int sep = fullPath.lastIndexOf(pathSeparator);
    return fullPath.substring(sep + 1, dot);
  }

  public String path() {
    int sep = fullPath.lastIndexOf(pathSeparator);
    return fullPath.substring(0, sep);
  }
}
drsmachado

Então, se o path passado se refere a algo que não existe, ele irá acusar nullpointerexception, certo?
Sendo assim, eu faria o catch como apenas Exception e, retornaria uma String “Não é um arquivo/diretório válido”.

C

drsmachado:
Então, se o path passado se refere a algo que não existe, ele irá acusar nullpointerexception, certo?
Sendo assim, eu faria o catch como apenas Exception e, retornaria uma String “Não é um arquivo/diretório válido”.

O codigo do jeito que esta aki… nao lanca excessao… ou seja nao sei se ta ok ou nao o diretorio ou arquivo

drsmachado

Passe um path diferente, algo do tipo

final String FPATH = "c:/test/fsdrgdfgthyjfgjfjguj";
C

drsmachado:
Passe um path diferente, algo do tipo

final String FPATH = "c:/test/fsdrgdfgthyjfgjfjguj";

Nada…Me retorna isso:

run:
CONSTRUÍDO COM SUCESSO (tempo total: 0 segundos)

dougfane
public class FilenameDemo {
  public static void main(String[] args) throws IOException {
    final String FPATH = "c:/asd/tc.txt";
    Filename myHomePage = new Filename(FPATH, '/', '.');
    File f = new File(myHomePage.path());

    try{
        if(!f.exists()){
            System.out.println("Path = " + myHomePage.path());
            System.out.println("DIRETORIO INEXISTENTE");
        }
    }catch(Exception e){
        System.err.println(e);
    }finally{
        try{
            if(f.isDirectory()){
                System.out.println("Path = " + myHomePage.path());
                System.out.println("DIRETORIO VALIDO");
            }else {
                System.out.println("Path = " + myHomePage.path());
                System.out.println("DIRETORIO INVALIDO");
            }
        }catch(Exception e){
            System.err.println(e);
        }        
    }

    f = new File(FPATH);
    try{
        if (!f.exists()){
            System.out.println("Filename = " + myHomePage.filename());
            System.out.println("Arquivo INEXISTENTE");
        }
    }catch(Exception e){
        System.err.println(e);
    }finally {
        try{
            if(f.isFile()){
                System.out.println("Filename = " + myHomePage.filename());
                System.out.println("Arquivo VALIDO");
            }else {
                System.out.println("Filename = " + myHomePage.filename());
                System.out.println("Arquivo INVALIDO");
            }
        }catch(Exception e){
            System.err.println(e);
        }
        try{
            if(f.canRead())
                System.out.println("pode ler");
        }catch(Exception e){
            System.err.println(e);
        }
    }
  }
}
C

Vw… pela ajuda…
Mas depurando isso ele nunca entra no catch ou seja se o arquivo o diretorio for invalido ele ta entrando no ele do try e nao no catch.

dougfane

Ahm… Você quer que gere uma Exception quando o arquivo ou o diretório não existir(em)? Se é isso, você precisa tentar “acessar” o arquivo pra gerar a exception FileNotFound ou NullPointer. Tente:

f = new File(FPATH); try{ new FileReader(f); System.out.println("Caminho VALIDO"); }catch(FileNotFoundException e){ System.out.println("Arquivo ou Diretório INEXISTENTE: "+e); }

Criado 29 de junho de 2011
Ultima resposta 29 de jun. de 2011
Respostas 13
Participantes 5