2013-10-05 29 views
1

我的源代碼中有一個方法用於處理目錄路徑和文件名。 有些路徑和文件名偶爾會用'''或'ñ'字符寫入。無法使用'''和'ñ'字符處理路徑或文件名

問題是具有特殊字符的目錄路徑不被識別爲目錄並被識別爲文件。 我偶爾需要讀取文件擴展名,並且當文件具有該字符時代碼不起作用,並且不能達到擴展名。

public static void listarDirectorio(File f, String separador) { 

    File[] ficheros = f.listFiles(); 
    File ficheroTratado = null; 

    logM.escribeLog(separador + "Ruta listada: " + f.getName(), false); 

    for (int x = 0; x < ficheros.length; x++) { 

     ficheroTratado = null; 
     ficheroTratado = ficheros[x]; 

     if (!ficheros[x].isDirectory()) { 
      if (esBorrable(ficheroTratado.getName())) { 
       // logM.escribeLog(
       //  "Fichero borrado: " + ficheroTratado.getName(), 
       // true); 
      } 
     } 

     if (ficheros[x].isDirectory() 
       && !ficheros[x].getName().startsWith("@")) { 

      String nuevo_separador; 
      nuevo_separador = separador + " # "; 
      listarDirectorio(ficheros[x], nuevo_separador); 
     } 
    } 
} 

public static boolean esBorrable(String nFichero) { 
    boolean esBorrable = false; 

    try { 
     String extension = ""; 
     int extIndex = nFichero.lastIndexOf("."); 
     String ruta = ""; 

     //logM.escribeLog("nombre de fichero: " + nFichero, false); 
     extension = nFichero.substring(extIndex, extIndex + 4); 
     //logM.escribeLog("extension que tengo: " + extension, false); 

     for (int i = 0; i < instance.getArrayExtensiones().size(); i++) { 
      ruta = ""; 
      ruta = instance.getArrayExtensiones().get(i); 

      if (ruta.equalsIgnoreCase(extension)) { 
       //(logM.escribeLog("Este es borrable", false); 
       esBorrable = true; 
      } else { 
       esBorrable = false; 
      } 
     } 
    } catch (Exception e) { 
     logM.escribeLog("Problema al tratar el fichero: " + nFichero, false); 
     e.printStackTrace(); 
     return false; 
    } 

    return esBorrable; 
} 

我希望你能幫我解決這個問題。

+1

我會注意到的一件事是,您可以使用[增強的for循環](https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with)來遍歷文件 - 「for(final File ficheroTratado:f .listFiles();)'。這將爲您節省4行代碼,並使其他**更具可讀性。 –

+0

可能有幫助:http://stackoverflow.com/questions/15642862/special-character-in-filename-are-not-supported-while-copying-using-uri –

+0

我不明白這個問題。你是說在文件名中包含''''或'ñ'的文件被錯誤地識別爲目錄嗎? –

回答

1

好的,我複製了你的問題,但它花了一些工夫!當語言環境或file.encoding與文件名的編碼不匹配時會發生此問題。請記住,在Linux中,文件系統名稱只是一個8位字符串,並沒有強制編碼。

要複製:

  1. Linux系統中,可能有一個EXT2/EXT3文件系統。在Windows 7 x64上沒有問題
  2. 使用Windows-1252/ISO-88591-15編碼創建一個名爲「dirñ」的目錄。這可以通過將Term模擬器(例如Putty)設置爲Windows-1252 Translation,然後:mkdir dirñ來完成。
  3. 設置您的區域,以`的en_US.UTF-8"
  4. 運行Java應用程序
  5. 目錄與非UTF-8字符他們將被歸類爲文件。

解決方案

它發現這是一個已知的錯誤,但唯一的解決方案是使用Java 7的NIO2實現:http://jcp.org/en/jsr/detail?id=203我已經測試過它,它確實按預期工作。按照新的世界秩序,您可以編寫一個目錄Filter這裏:http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#filter

替代解決方案是將所有文件名都轉換爲相同的編碼,例如UTF-8,並確保您的語言環境匹配。麻煩的是,如果您知道現有的編碼是什麼,並且您的文件是一致的,那麼只能轉換爲新的編碼。

+0

謝謝。我解決了在操作系統中將語言環境值更改爲es_ES.utf8的問題。只需在.profile中添加幾行即可 – rrnieto

相關問題