如何将导出的Java对象的格式更改为文件?

问题描述 投票:0回答:3

我正在尝试将Java对象导出到txt文件中,但是该文件中的输出格式不正确,并且包含不必要的数据。如果有人可以告诉我我在做什么错。因此,这是代码的简单示例:

import java.io.Serializable;

public class Test implements Serializable{

    private static final long serialVersionUID = 1L;
    private String shortName;
    private String fullName;


    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;
    }

}

这是方法的一部分:

FileOutputStream outputStream = new FileOutputStream(fullPath);
        ObjectOutputStream o = new ObjectOutputStream(outputStream);
        Test test = new Test("Short name of test","Full name of test");
        o.writeObject(test);
        o.close();
        outputStream.close();

这就是我在文件中得到的:

’ sr &com.testing.project.Evaluation.model.Test        L fullNamet Ljava/lang/String;L     shortNameq ~ xpt Full name of testt Short name of test

我将不胜感激。

java serialization objectoutputstream
3个回答
1
投票

您正在使用Java序列化,该对象将对象写入其自己的二进制格式,而不是文本。如果您需要文本格式,建议您使用带有jackson-databind之类的库的JSON。


0
投票

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();
    }

0
投票

writeObject函数将Test的对象图写入文件流。它用于JAVA中的持久性。如果要将字段数据存储到文件中,建议您在类中使用FileWriter使用专用方法。

© www.soinside.com 2019 - 2024. All rights reserved.