我的源代碼中有一個方法用於處理目錄路徑和文件名。 有些路徑和文件名偶爾會用'''或'ñ'字符寫入。無法使用'''和'ñ'字符處理路徑或文件名
問題是具有特殊字符的目錄路徑不被識別爲目錄並被識別爲文件。 我偶爾需要讀取文件擴展名,並且當文件具有該字符時代碼不起作用,並且不能達到擴展名。
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;
}
我希望你能幫我解決這個問題。
我會注意到的一件事是,您可以使用[增強的for循環](https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with)來遍歷文件 - 「for(final File ficheroTratado:f .listFiles();)'。這將爲您節省4行代碼,並使其他**更具可讀性。 –
可能有幫助:http://stackoverflow.com/questions/15642862/special-character-in-filename-are-not-supported-while-copying-using-uri –
我不明白這個問題。你是說在文件名中包含''''或'ñ'的文件被錯誤地識別爲目錄嗎? –