3 回答

TA貢獻1809條經驗 獲得超8個贊
您正在使用 Java 序列化,它將對象寫入其自己的二進制格式,而不是文本。如果您需要文本格式,我建議您使用 JSON 以及jackson-databind等庫。
為了方便起見,這里是一個工作示例(既寫入文本文件又從文本文件讀回對象):
主類
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
? ? public static void main(String[] args) throws JsonGenerationException, JsonMappingException, FileNotFoundException, IOException {
? ? ? ? ObjectMapper om = new ObjectMapper();
? ? ? ? Test test = new Test("Short name of test","Full name of test");
? ? ? ? om.writeValue(new FileOutputStream("test.json"), test);
? ? ? ? Test readValue = om.readValue(new FileInputStream("test.json"), Test.class);
? ? ? ? System.out.println(readValue.getShortName());
? ? ? ? System.out.println(readValue.getFullName());
? ? }
}
測試類
import java.io.Serializable;
public class Test implements Serializable{
? ? private static final long serialVersionUID = 1L;
? ? private String shortName;
? ? private String fullName;
? ? public Test() {
? ? }
? ? public Test(String shortName, String fullName) {
? ? ? ? this.shortName=shortName;
? ? ? ? this.fullName=fullName;
? ? }
? ? public String getShortName() {
? ? ? ? return shortName;
? ? }
? ? public void setShortName(String shortName) {
? ? ? ? this.shortName = shortName;
? ? }
? ? public String getFullName() {
? ? ? ? return fullName;
? ? }
? ? public void setFullName(String fullName) {
? ? ? ? this.fullName = fullName;
? ? }
? ? @Override
? ? public String toString() {
? ? ? ? return "Name:" + shortName +? ?"\nFullName: " + fullName;
? ? }
}
請注意,我已向 Test.class 添加了一個默認構造函數,以便 Jackson 可以在從 json 反序列化時創建它。

TA貢獻1847條經驗 獲得超11個贊
writeObject 函數將 Test 的對象圖寫入文件流。在JAVA中用于持久化。如果您想將字段數據存儲到文件中,我建議您在類中使用 FileWriter 的專用方法。

TA貢獻1811條經驗 獲得超5個贊
ObjectOutputStream不會以可讀格式寫入。您可能想使用FileWriter:
try (BufferedWriter writer = new BufferedWriter(new FileWriter("test.txt"))) {
Test t = new Test("Short name of test", "Full name of test");
writer.write(t.toString());
} catch (IOException e) {
e.printStackTrace();
}
添加回答
舉報