How to open files with accent on name - Filenotfoundexception

Asked

Viewed 54 times

1

The path to the files are in a String array. Some files have accented name and are generating FileNotFoundException

   /**
    * Realiza leitura dos dados de um arquivo.
    * @param s - string com endereco do diretorio do arquivo    
    */
   public void ler(String s) {

      String dados = "";
      String linha;

      try {

         FileReader f = new FileReader(s);
         BufferedReader b = new BufferedReader(f);

         while(b.ready()){

            linha = b.readLine();
            dados += linha;
         }

         this.dados = dados;

         b.close();
         f.close();

      } catch (IOException e) {

         MyIO.println("METODO LER() ====> " + e.toString());

      } finally{
      }  
   }

Example of file names:

/tmp/personagens/Cordé.txt
/tmp/personagens/Dormé.txt
/tmp/personagens/JabbaDesilijicTiure.txt
/tmp/personagens/JangoFett.txt
/tmp/personagens/JarJarBinks.txt
/tmp/personagens/PadméAmidala.txt
/tmp/personagens/RicOlié.txt

1 answer

3


You need to convert the String with the File name to UTF-8:

byte[] isoBytes = strISO.getBytes("ISO-8859-1");
String ISOtoUTF = new String(isoBytes, "UTF-8");

Use in the code:

   public void ler(String s) {

      String dados = "";
      String linha;

      try {

         byte [] isoBytes = s.getBytes("ISO-8859-1");
         FileReader f = new FileReader(new String(isoBytes, "UTF-8"));
         BufferedReader b = new BufferedReader(f);

         while(b.ready()){

            linha = b.readLine();
            dados += linha;
         }

         this.dados = dados;

         b.close();
         f.close();

      } catch (IOException e1) {    
         MyIO.println(e1.toString());    
      } catch (UnsupportedEncodingException e2) {    
         MyIO.println(e2.toString());    
      } finally{
      }  
   }

Browser other questions tagged

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