Creating file with non english characters in the f

2019-08-07 16:02发布

问题:

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.