JFileChooser on Mac cannot see files named by Chinese chars?

大憨熊 提交于 2019-12-02 12:34:54

问题


The program worked fine when running in Intellij (it can see the Chinese named files).

I built it into a .jar file. Executed the jar and the JFileChooser cannot see those files.

And I tried the jar in Windows, it works completely fine.


回答1:


This works file for me on Mac OS X 10.8.2:

import java.io.File;
import javax.swing.JFileChooser;
public class JFileChooserTest
{
  public static void main(String[] args)
  {
    System.out.println("file.encoding=" + System.getProperty("file.encoding"));
    String path;

    if(args.length > 0)
      path = args[0];
    else
      path = System.getProperty("user.dir", ".");

    File dir = new File(path);

    JFileChooser jfc = new JFileChooser(dir);
    int result = jfc.showOpenDialog(null);

    switch(result) {
      case JFileChooser.CANCEL_OPTION:
        System.out.println("User cancelled OPEN dialog.");
        break;
      case JFileChooser.APPROVE_OPTION:
        System.out.println("User chose file: " + jfc.getSelectedFile());
        break;
      case JFileChooser.ERROR_OPTION:
        System.out.println("User encountered an error");
        break;
     default:
       System.out.println("Confused");
       break;
    }

    System.exit(0);
  }
}

Here's a sample run:

$ java -showversion JFileChooserTest 
java version "1.7.0_09"
Java(TM) SE Runtime Environment (build 1.7.0_09-b05)
Java HotSpot(TM) 64-Bit Server VM (build 23.5-b02, mixed mode)

file.encoding=UTF-8
User chose file: /.../测试文件.txt

Here's another sample run:

$ java -showversion -Dfile.encoding=ISO-8859-1 JFileChooserTest 
java version "1.7.0_09"
Java(TM) SE Runtime Environment (build 1.7.0_09-b05)
Java HotSpot(TM) 64-Bit Server VM (build 23.5-b02, mixed mode)

file.encoding=ISO-8859-1
User chose file: /.../????.txt

In both cases, the file-selection dialog properly displayed the name of the file (测试文件.txt).

Note that using java.awt.FileDialog will get you the platform-specific file dialog that most Mac OS users are used to seeing. Though it's not strictly Swing (and has an abysmally small feature set), it is probably superior to JFileChooser for things like OPEN and SAVE dialogs. (It also shows Chinese characters without a problem on my system).



来源:https://stackoverflow.com/questions/14072619/jfilechooser-on-mac-cannot-see-files-named-by-chinese-chars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!