1

我想我需要使用

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF8"));

但是当我将代码更改为 BufferedWriter 时,该行出现了问题out.write(e);

我的代码:

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();
        }
    }

它在文件中显示的内容:

//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$

我希望它显示的是:

//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$

如何将 utf-8 写入文件并将“3”更改为“03”?

4

5 回答 5

3

03(前导零)而不是3你可以使用

int myInteger = 3;
out.println("Some value: " + String.format("%02d", myInteger) );

有关语法的详细信息,请参阅String.format(...) 文档

于 2013-10-19T13:50:30.753 回答
0

由于您已经知道应该使用 BufferedWriter,因为它让您选择了编码,所以我看不出这里有什么问题。

我只想补充一点,而不是将“UTF8”写成一个容易出错的字符串,从 Java 1.7 开始,你可以使用StandardCharsets类来获取所有标准字符集:-)

如果 Java 1.7 不是一个选项,您也可以使用 Guava 的Charsets类。

于 2013-10-19T14:36:46.547 回答
0

Use,

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path),"UTF-8"));

that way you can set the encoding.

于 2013-10-19T13:47:30.447 回答
0

You need to use the charset names mentioned at this link

It says the standard charsets as "UTF-8" and not "UTF8".

So change it to "UTF-8" and it will work.

Below for your reference :

  • US-ASCII
    Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set
  • ISO-8859-1
    ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
  • UTF-8
    Eight-bit UCS Transformation Format
  • UTF-16BE
    Sixteen-bit UCS Transformation Format, big-endian byte order
  • UTF-16LE
    Sixteen-bit UCS Transformation Format, little-endian byte order
  • UTF-16
    Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark
于 2013-10-19T13:48:15.903 回答
0

尝试这个

Writer out = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream("outfilename"), "UTF-8"));
try {
    out.write(aString);
} finally {
    out.close();
}
于 2013-10-19T13:50:10.550 回答