我正在嘗試使用 FileOutputStream 創建一個檔案,但它總是創建如下圖所示的 ANSI 格式。我在 Eclipse 和 IntelliJ 上進行了所有字符編碼設定,但仍然是同樣的問題。

這是我的代碼:
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
public class sss {
public static void main(String args[]){
try{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success");
}catch(Exception e){System.out.println(e);}
}
}
uj5u.com熱心網友回復:
不要在ObjectOutputStream那里使用;那是針對二進制Java物件的。避免可序列化;它實際上已被棄用。Serializable 也存盤類資料。
try (FileOutputStream fout=new FileOutputStream("f.txt")) {
fout.write(s1.name.getBytes(StandardCharsets.UTF_8));
} // Closes fout.
“錯誤”可能是由于最新的 String 類,它將保存 Unicode,通常作為 UTF-16 字符陣列,也可以保存 ANSI 位元組陣列。
您還硬編碼了一個字串 ( new Student(211,"ravi");),這意味著保存 java 源代碼的編輯器和 javac 編譯器必須使用相同的編碼來生成 .class 檔案。如果不是,字串將被損壞。
try {
//Creating the object
Student s1 = new Student(212, "Jérome");
//Creating stream and writing the object
Path path = Paths.get("f.txt");
Files.writeString(path, s1.name); // Default UTF-8
path = path.resolveSibling("f-latin1.txt");
Files.writeString(path, s1.name, StandardCharsets.ISO_8859_1);
System.out.println("success");
} catch (Exception e) {
e.printStackTrace(System.out);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/510523.html
標籤:爪哇UTF-8编码安西
