Search code examples
javafilespecial-charactersreadfile

.listFiles() returned file object returns false on .exists() - file contains special character(s)


I've got a java application zipping a given directory. A file is omitted containing a special character (e.g. an umlaut - ä, ö, etc.). Debugging showed, that the file is omitted because it does not exist

if(file.exists()) {
  //zip it
} else {
  System.err.println("file " + file.getAbsolutePath() + " does not exist!");
}

The thing is - I retrieve the file object from

File[] files = directory.listFiles();

and then iterrate through them.

for(File file : files) {
  if(file.exists()) {
    //zip file
  } else {
    System.err.println("...");
  }
}

What I saw is, that file.getAbsolutePath() shows me the following path /tmp/myspecialChar?File.txt instead of /tmp/myspecialCharÖFile.txt.

Any ideas how to get hold of the File. Unfortunately all special characters will be translated into "?" so I cannot implement a mapping. Listing names returns also "?" instead of the correct special character.

Before I forget - the JVM version is 1.6.31.


Solution

  • You need to set the file.encoding system property of your JVM

    -Dfile.encoding=UTF-8
    

    Please, note this has to be done at the start-up as a java parameter. Doing it later with a System.setProperty() won't help as the value (that comes from the host OS) is already cached by then.