Object.toString() 然后编码为UTF-8

Object.toString() then, encode to UTF-8

我正在尝试实现一种将对象转换为字符串的方法,然后将此字符串编码为 UTF-8 并转换为 .txt。到目前为止,我能够让它工作,但是写入输出文件的内容似乎不正常......我错过了什么?

编辑:代码已编辑,现在我从文件中得到它;

阿森纳 W 10 L 02 D 03 GF 45 GA 05Chelsea W 08 L 02 D 05 GF 17 GA 03Aston Villa W 05 L 05 D 05 GF 05 GA 09Hull City W 06 L 04 D 05 GF 30 GA 15Inverness Caledonian Thistle W 11 L 02 D 07 GF 50 GA 20

static void writeToDisk() throws ClassNotFoundException, IOException {

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

        for(FootballClubNL club : deserializeFromDisk()){

            String clubString = club.toString();

            out.append(clubString).append("\r\n");
            out.flush();    
        }
        out.close();
    }

您似乎混淆了编写文本和编写二进制文件。你有多种操作。我建议您选择一个或另一个,否则您一定会感到困惑。

你遇到的问题是 byte[] 没有非常有用的 toString() 甚至 Arrays.toString 也不会做你想做的事。

我怀疑您不需要 UTF-8 编码,除非您的 toString() 非常不寻常。

写成文字

try(PrintWriter pw = new PrintWriter(filename_2)) {
    for(FootballClubNL club : deserializeFromDisk())
        pw.println(club);
}

写成二进制

try(OutputStream out = new FileOutputStream(filename_2)) {
    for(FootballClubNL club : deserializeFromDisk())
        out.write(club.toString().getBytes());
}

您没有在任何地方指定编码:

byte[] b = clubString.getBytes(StandardCharsets.UTF_8);

您的代码还有其他问题。您的方法的更简单版本是:

List<String> lines = new ArrayList<>();
for(FootballClubNL club : deserializeFromDisk()){
    lines.add(club.toString());
}
Files.write(Paths.get(filename_2), lines, StandardCharsets.UTF_8);