问题描述
如何用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:
- 用于保存源文件的编码能够表示这些字符(我的建议是坚持使用UTF-8)
-
您传递给
javac
的-encoding
参数应与文件的编码匹配.例如,如果使用UTF-8,则javac命令应类似于
- The encoding you use to save the source file is capable to represent those character (My suggestion is just to stick with UTF-8)
The
-encoding
parameter you passed tojavac
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.
这篇关于创建文件名中非英文字符的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!