Skip file when entering an Exception

Asked

Viewed 74 times

1

Good afternoon

Below is a method I use to read certain files from a folder. The problem is as follows. If the folder has 50 files (or 60, or 70, or 80 ...) and the method is reading a "faulty" file (one of the files that fall into Exeception), the method hangs on this file and does not consume the others. I would like that when entering one exception, the stream continued, and then came back in that file. If it was OK, it consumes, if not, it jumps back to the others.

public static String lerPasta() throws FileNotFoundException{
      String texto = null;  
        try{    
            FileFilter filter = new FileFilter() {
            public boolean accept(File file) {
                return file.getName().endsWith(".XML");
                }
            };
            File dir = new File(diretorioIn);
               File[] files = dir.listFiles(filter);

            for(i = 0; i < files.length ; i++){
                Scanner s = new Scanner(new File(files[i].toString()), "UTF-8");
                texto = s.useDelimiter("\\A").next();     
                System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+"VALOR DE I" +i);
                verificaTipoXML(files[i].toString().substring(diretorioIn.length()));
                System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+" verificaTipoXML:files[i].toString(): "+files[i].toString());
                System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+" lerPasta():" + files[i].toString());
                System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+" verificaTipoXML():" + files[i].toString().substring(diretorioIn.length()+0));
                deleta = files[i].toString();
                //+1
                deleta2 = files[i].toString().substring(diretorioIn.length());
                deletar = files[i];
                System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+" deleta:"+deleta2);
                nomegerado = files[i].toString().substring(diretorioIn.length()+3);
                System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+" GLOBAL:nomegerado:" + nomegerado);
                s.close();
             }

        }catch(FileNotFoundException e){
                 System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+"lerPasta():ERRO: FileNotFoundException : Tentando novamente ...");
        }    
        catch(NoSuchElementException e){
             System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+"lerPasta():ERRO: NoSuchElementException : Tentando novamente ...");

        }
        return texto;
    }

2 answers

1

Your method is locking because your Try/catch is out of the for and when an exception is thrown, the loop is stopped. Just move Try/catch inside the for and it will try to read all the files.

In order for it to try again to read the files that fail, you can store them in a list and then try to read them again. It would be something like this:

public static String lerPasta() {

    FileFilter filter = new FileFilter() {
        public boolean accept(File file) {
            return file.getName().endsWith(".pdf");
        }
    };

    File dir = new File(FILE_PATH);
    Iterator<File> files = Arrays.asList(dir.listFiles(filter)).iterator(); 
    List<File> failedFiles = new ArrayList<>();

    while(files.hasNext()) {
        File file = files.next();
        try(Scanner s = new Scanner(new File(file.toString()), "UTF-8")) {
            //Faça o que quiser aqui
            //...
        } catch (FileNotFoundException | NoSuchElementException e) {
            if(failedFiles != null) {
                failedFiles.add(file);
            }
        } finally {
            if(!files.hasNext() && failedFiles != null && !failedFiles.isEmpty()) {
                files = failedFiles.iterator();
                failedFiles = null;
            }
        }
    }

}
  • Remember to put a control on how often you will try to read the files that failed so you don’t get looping trying to read a failed file.

  • @Gabrielweber, the algorithm will only try to read the files that fail once, since when they start to be read again it is assigned null the list of failed files and no other element is attributed to it. But yes, if you want to have more control over the number of attempts, you would need some additions to the algorithm.

  • it is true, you are right! It became very elegant this its solution, very well.

0

It will crash because the for is inside the Try-catch, as soon as the exception is launched(FileNotFoundException or NoSuchElementException ), he will come out of the go and enter the catch.

Try to do that from there. I took the for out of the catch, and put another in it (do for). This Try-catch inside the for will ignore the "faulty files".

Just to remind, it’s not cool to use pure Try-catch, IE, hiding exception, the reason has to be very good.

public static String lerPasta() throws FileNotFoundException{
      String texto = null; 
      File[] files = null;    
        try{    
            FileFilter filter = new FileFilter() {
            public boolean accept(File file) {
                return file.getName().endsWith(".XML");
                }
            };
            File dir = new File(diretorioIn);
               File[] files = dir.listFiles(filter);

        }catch(FileNotFoundException e){
                 System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+"lerPasta():ERRO: FileNotFoundException : Tentando novamente ...");
        }    
        catch(NoSuchElementException e){
             System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+"lerPasta():ERRO: NoSuchElementException : Tentando novamente ...");
        }

        if(files == null){
            //Lança algum erro.
        }

        for(i = 0; i < files.length ; i++){
            try{
                Scanner s = new Scanner(new File(files[i].toString()), "UTF-8");
                texto = s.useDelimiter("\\A").next();     
                System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+"VALOR DE I" +i);
                verificaTipoXML(files[i].toString().substring(diretorioIn.length()));
                System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+" verificaTipoXML:files[i].toString(): "+files[i].toString());
                System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+" lerPasta():" + files[i].toString());
                System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+" verificaTipoXML():" + files[i].toString().substring(diretorioIn.length()+0));
                deleta = files[i].toString();
                //+1
                deleta2 = files[i].toString().substring(diretorioIn.length());
                deletar = files[i];
                System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+" deleta:"+deleta2);
                nomegerado = files[i].toString().substring(diretorioIn.length()+3);
                System.out.println(ZonedDateTime.now(fusoHorarioDeSaoPaulo)+" GLOBAL:nomegerado:" + nomegerado);
            }catch(AlgumaException e){
                //Não faz nada.
            }finally{
                s.close();
            }
        }
    return texto;
}

Browser other questions tagged

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