[英]Object.toString() then, encode to UTF-8
我正在嘗試實現一種將對象轉換為字符串的方法,然后將該字符串編碼為UTF-8並轉換為.txt。 到目前為止,我能夠使其工作,但是寫入輸出文件中的內容似乎還不行。。。我缺少什么?
編輯:代碼已編輯,現在我從文件中獲取了代碼;
阿森納W 10 L 02 D 03 GF 45 GA 05切爾西W 08 L 02 D 05 GF 17 GA 03阿斯頓維拉W 05 L 05 D 05 GF 05 GA 09赫爾城W 06 L 04 D 05 GF 30 GA 15因弗內斯加里東薊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[] 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);
您似乎對編寫文本和編寫二進制文件感到困惑。 您需要多種操作。 我建議您選擇其中一個,否則您一定會感到困惑。
您遇到的問題是, byte[]
沒有非常有用的toString()
甚至Arrays.toString
也無法滿足您的要求。
我懷疑除非您的toString()非常不尋常,否則您不需要UTF-8編碼。
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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.