I have a problem using File.list() with file names with NON-ASCII characters incorrectly retrieved on Mac OS X when using Java 7 from Oracle.
I am using the following example:
import java.io.*;
import java.util.*;
public class ListFiles {
public static void main(String[] args)
{
try {
File folder = new File(".");
String[] listOfFiles = folder.list();
for (int i = 0; i < listOfFiles.length; i++)
{
System.out.println(listOfFiles[i]);
}
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Running this example with Java 6 from Apple, everything is fine:
....
Folder-ÄÖÜäöüß
吃饭.txt
....
Running this example with Java 7 from Oracle, the result is as follows:
....
Folder-A��O��U��a��o��u����
������.txt
....
But, if I set the environment as follows (not set in the two cases above):
LANG=en_US.UTF-8
the result with Java 7 from Oracle is as expected:
....
Folder-ÄÖÜäöüß
吃饭.txt
....
My problem is that I don't want to set the LANG environment variable. It's a GUI application that I want to deploy as an Mac OS X application, and doing so, the LSEnvironment setting
<key>LSEnvironment</key>
<dict>
<key>LANG</key>
<string>en_US.UTF-8</string>
</dict>
in Info.plist takes no effect (see also here)
What can I do to retrieve the file names correctly in Java 7 from Oracle on Mac OS X without having to set the LANG environment? In Windows and Linux, this problem does not exist.
EDIT:
If I print the individual bytes with:
byte[] x = listOfFiles[i].getBytes();
for (int j = 0; j < x.length; j++)
{
System.out.format("%02X",x[j]);
System.out.print(" ");
}
System.out.println();
the correct results are:
Folder-ÄÖÜäöüß
46 6F 6C 64 65 72 2D 41 CC 88 4F CC 88 55 CC 88 61 CC 88 6F CC
88 75 CC 88 C3 9F
吃饭.txt
E5 90 83 E9 A5 AD 2E 74 78 74
and the wrong results are:
Folder-A��O��U��a��o��u����
46 6F 6C 64 65 72 2D 41 EF BF BD EF BF BD 4F EF BF BD EF BF BD
55 EF BF BD EF BF BD 61 EF BF BD EF BF BD 6F EF BF BD EF BF BD
75 EF BF BD EF BF BD EF BF BD EF BF BD
������.txt
EF BF BD EF BF BD EF BF BD EF BF BD EF BF BD EF BF BD 2E 74 78 74
So one can see that Files.list() replaces some bytes with UTF-8 "EF BF BD" = Unicode U+FFFD = Replacement Character, if LANG is not set (only Java 7 from Oracle).