我有创建PrintWriter并打印Unicode符号的代码
out = new PrintWriter(new FileWriter("test.txt"));
out.print("\u2588");
out.close();
它在eclipse中使用UTF-8编码保存时效果很好,但是当我将它导出到jar时,它只会打印掉问号。在打印字符串时如何告诉它使用UTF-8?
答案 0 :(得分:3)
Eclipse可能会帮助您创建UTF-8编码文件,但最好在代码中使用正确的编码。
FileWriter不接受任何编码参数。您可以使用OutputStreamWriter,因为它也接受编码。您可以将PrintWriter初始化更改为:
PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream("test.txt"),"UTF-8")));
答案 1 :(得分:0)
创建FileOutputStream而不是FileWriter。然后将它包装在OutputStreamWriter中,它允许您在构造函数中传递编码。
FileOutputStream fos = new FileOutputStream("test.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8")
PrintWriter out = new PrintWriter(osw);