![](/img/trans.png)
[英]Is ObjectOutputStream.writeObject to a file thread safe?
[英]Java, ObjectOutputStream.writeObject prints random symbols to file
public class Customer {
public static void main(String[] args) throws IOException {
FileOutputStream a = new FileOutputStream("customer.txt");
ObjectOutputStream b = new ObjectOutputStream(a);
human Iman = new human("Iman",5000);
human reda = new human("reda",5555);
b.writeObject(Iman); //prints random symbols.
b.writeObject(reda);
}
}
class human implements Serializable{
private String name;
private double balance;
public human(String n,double b){
this.name=n;
this.balance=b;
}
}
這些隨機符號代表什么?
是的,您正在嘗試存儲對象本身,因此正在存儲二進制格式。
要實際以文本格式存儲數據,請使用以下代碼BufferedWriter,如下所示:
public void writeHumanStateToFile(Human human){
try{
File file = new File("filename.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(human.getName);
bw.write(human.getBalance);
bw.newLine();
bw.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
我假設您要堅持人類對象的狀態。
您正在使用ObjectOutputStream
。 那不會產生文本-它會產生數據的二進制序列化版本。 如果確實需要文本表示形式,則需要使用其他方法。
如果您對二進制數據沒問題,請保持原樣-也許更改文件名以減少誤導。 您可以使用ObjectInputStream
再次讀取數據。
數據格式在“ 對象序列化流協議”文檔中描述。 正如您已經指出的那樣,它不是人類可讀的。
如果要以可讀格式進行序列化,則可以使用java.beans.XMLEncoder
或類似Pojomatic的東西。
您正在序列化對象。 它不是以純文本形式可讀,而是二進制格式,可以很容易地讀取對象並在以后執行程序時重新創建它。
如果要以純文本格式存儲對象,則需要將對象的各個字段寫入文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.