我正在尝试实现一个将对象转换为字符串的方法,然后将此字符串编码为UTF-8为.txt。到目前为止,我能够使它工作,但写入输出文件的内容似乎没有问题......我缺少什么?
编辑:编辑了代码,现在我从文件中得到了这个;
Arsenal 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();
}
答案 0 :(得分:5)
您没有在任何地方指定编码:
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);
答案 1 :(得分:3)
您似乎将写入文本与写入二进制文件混淆了。你有各种各样的操作。我建议你选择其中一个,否则你一定会感到困惑。
您遇到的问题是,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());
}