Creating file with non english characters in the file name

别说谁变了你拦得住时间么 提交于 2020-01-05 10:13:06

问题


How to create a file with chinese character in file name in Java? I have read many stack overflow answers but couldn't find a proper solution. The code I have written till now is as follows:

private void writeFile(String fileContent) {
try{
    File file=new File("C:/temp/你好.docx");
        if(file.exists()){
            file.delete();
        }
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(fileContent);
        fos.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

The file is written to the output directory but the name of the file contains some garbage value. Thanks in advance.


回答1:


I believe the key is as what I have mentioned in the comment.

You can have Chinese characters (or other non-ascii character) as literals in source code. However you should make sure two things:

  1. The encoding you use to save the source file is capable to represent those character (My suggestion is just to stick with UTF-8)
  2. The -encoding parameter you passed to javac should match the encoding of the file. For example, if you use UTF-8, your javac command should looks like

    javac -encoding utf-8 Foo.java

I have just tried a similar piece of code you have, and it works well in my machine.



来源:https://stackoverflow.com/questions/20257539/creating-file-with-non-english-characters-in-the-file-name

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