创建文件名中非英文字符的文件 [英] Creating file with non english characters in the file name

查看:106
本文介绍了创建文件名中非英文字符的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用Java在文件名中创建带有中文字符的文件?我已经阅读了很多堆栈溢出答案,但是找不到合适的解决方案.我到目前为止编写的代码如下:

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.

推荐答案

我相信关键在于我在评论中提到的内容.

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

您可以在源代码中将汉字(或其他非ascii字符)作为文字.但是,您应该确保两件事:

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

  1. 用于保存源文件的编码能够表示这些字符(我的建议是坚持使用UTF-8)
  2. 您传递给javac-encoding参数应与文件的编码匹配. 例如,如果使用UTF-8,则javac命令应类似于

  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.

这篇关于创建文件名中非英文字符的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆