[英]How to write file UTF8?
I think I need to use 我想我需要用
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF8"));
But when I change my code to BufferedWriter, then something is wrong with the line out.write(e);
但是当我将代码更改为BufferedWriter时,行
out.write(e);
. 。
My code: 我的代码:
public void writeToFile(String fileName, List<ThongtinKhachThue> resultttkt){
System.out.println("Begin....");
try {
PrintWriter out = new PrintWriter(new File(fileName));
out.println("//thue.txt");
for(ThongtinKhachThue e : resultttkt){
out.println(e);
}
out.println("Tổng khách thuê phòng: "+TongKhachThue());
out.println("Tổng tiền thu: "+TongTienThuDuoc()+"$");
out.flush();
out.close();
System.out.println("End...");
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
what it shows in file: 它在文件中显示的内容:
//thue.txt
K1, A1002, 47.05$
K2, A0003, 67.0$
K3, A1001, 31.0$
K4, null, 0.0$
T?ng khách thuê ph?ng: 3
T?ng ti?n thu: 145.05$
what I want it to show is: 我希望它展示的是:
//thue.txt
K1, A1002, 47.05$
K2, A0003, 67.0$
K3, A1001, 31.0$
K4, Không thuê
Tổng khách thuê: 03
Tổng tiền thu: 145.05$
How can i write utf-8 to file and change "3" to "03"? 如何将utf-8写入文件并将“3”更改为“03”?
To write 03
(leading zero) instead of 3
you can use 要写
03
(前导零)而不是3
你可以使用
int myInteger = 3;
out.println("Some value: " + String.format("%02d", myInteger) );
See String.format(...) documentation for details on the syntax. 有关语法的详细信息,请参见String.format(...)文档 。
Use, 采用,
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path),"UTF-8"));
that way you can set the encoding. 这样你就可以设置编码。
You need to use the charset names mentioned at this link 您需要使用此链接中提到的字符集名称
It says the standard charsets as "UTF-8" and not "UTF8". 它说标准字符集为“UTF-8”而不是“UTF8”。
So change it to "UTF-8" and it will work. 因此将其更改为“UTF-8”,它将起作用。
Below for your reference : 以下供您参考:
Try this 尝试这个
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("outfilename"), "UTF-8"));
try {
out.write(aString);
} finally {
out.close();
}
Since you already know that you should use a BufferedWriter since it let's you chose the encoding I do not see what's the problem here. 既然你已经知道你应该使用BufferedWriter,因为它让你选择了编码,我不知道这里有什么问题。
I would only like to add that instead of writing "UTF8" as a string which is error prone you can use, as of Java 1.7, the class StandardCharsets to get, well, all the standard charsets :-) 我只想补充一点,而不是写“UTF8”作为一个容易出错的字符串,你可以使用,从Java 1.7开始,类StandardCharsets得到,以及所有标准字符集:-)
If Java 1.7 isn't an option you can also use Guava's Charsets class. 如果Java 1.7不是一个选项,您也可以使用Guava的Charsets类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.