java 如何将对象编写为人类可读的文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16817210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:04:31  来源:igfitidea点击:

How to write Object as human readable text file

javaserializationfile-io

提问by violet kiwi

I want to write objects in human readable form in a text file, the file gets saved as a normal serialized object with unwanted characters instead.

我想在文本文件中以人类可读的形式编写对象,该文件被保存为带有不需要的字符的普通序列化对象。

How do I rewrite the program for saving into human readable text file?

如何重写程序以保存到人类可读的文本文件中?

import java.io.*;
class book implements Serializable 
{
    String name;
    String author;
    int nop;
    int price;
    int discount;

    void getDiscount()
    {
        int finalprice=price-((price/discount));
        System.out.println("Final price after discount="+finalprice);
    }

    public String toString()
    {
        return name+author+nop+price+discount;
    }
}

class fileio
{
    public static void main(String args[])
    {
        MainClass mainObject=new MainClass();
        mainObject.writeToFile();
        book javabook=new book();
        javabook.name="Java unleashed";
        javabook.author="someone";
        javabook.nop=1032;
        javabook.price=450;
        javabook.discount=10;
        javabook.getDiscount();
    }
        public void writeToFile()
        {
        try
        {
        File file=new File("JavaBook1.txt");
        FileWriter fw=new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw=new BufferedWriter(fw);
        bw.write(book.toString());
        bw.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}

回答by Kai

You could serialize it as XML by using JAXBor XStream. XML is more human-readable as binary data so maybe XML is ok for you. Assuming you also want to deserialize your data this is a good option.

您可以使用JAXBXStream将其序列化为 XML 。XML 作为二进制数据更易于人类阅读,因此也许 XML 适合您。假设您还想反序列化您的数据,这是一个不错的选择。

回答by M Sach

See if below solves your purpose

看看下面是否能解决你的目的

override toString() method of Object class to return your object's state and then write the output of it to text file with file writer

覆盖对象类的 toString() 方法以返回对象的状态,然后使用文件编写器将其输出写入文本文件

If you want to have xml kind of representatio, go for JAXB approach

如果你想要 xml 类型的表示,请使用 JAXB 方法

Update:-

更新:-

please ignore syntax/compile errors in below program as i have not tested it but it will give you brief idea

请忽略下面程序中的语法/编译错误,因为我还没有测试过它,但它会给你一个简短的想法

class Book
{
    String name;
    String author;
    int nop;
    int price;
    int discount;

    void getDiscount()
    {
        int finalprice=price-((price/discount));
        System.out.println("Final price after discount="+finalprice);
    }

    public String toString() {
    return name + author +nop + price +discount;
    // above can be any format whatever way you want


    }
}

Now in your main class

现在在你的主班

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

class Fileio
{
    public static void main(String args[])
    {
        Fileio mainObject=new Fileio();

        Book javabook=new book();
        javabook.name="Java unleashed";
        javabook.author="someone";
        javabook.nop=1032;
        javabook.price=450;
        javabook.discount=10;
        javabook.getDiscount();
        mainObject.writeToFile(javabook);
    }
        public void writeToFile(Book javabook)
        {
        try
        {
        File file=new File("JavaBook1.txt");
        FileWriter fw=new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw=new BufferedWriter(fw);
        bw.write(javabook.toString());
        bw.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

回答by marmots

Two easy options:

两个简单的选择:

in your code:

在您的代码中:

ReflectionToStringBuilder.toString(javabook, ToStringStyle.MULTI_LINE_STYLE);

will produce:

将产生:

org.marmots.application.generator.Book@77459877[
  name=Java unleashed
  author=someone
  nop=1032
  price=450
  discount=10
]

that's nice for debugging. If you have only simple fields it will be enough; if you reference another bean inside it (and another, and another...), it will print its toString() method, so you can override toString method for all your value/transfer objects with this code in order to have nice reading methods for all).

这对调试很好。如果你只有简单的字段就足够了;如果您在其中引用另一个 bean(以及另一个和另一个...),它将打印其 toString() 方法,因此您可以使用此代码覆盖所有值/传输对象的 toString 方法,以便获得良好的阅读方法对所有人)。

what I do usually is to extend from a base bean class:

我通常做的是从基础 bean 类扩展:

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

public abstract class ToStringReadable {
  @Override
  public String toString() {
    return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
  }
}

extending ToStringReadable will make all your beans human readable for debugging purposes.

扩展 ToStringReadable 将使您的所有 bean 可读以进行调试。

In your code (note that you will have to publish your attributes with getter/setter(s), it's a good practice so even better):

在您的代码中(请注意,您必须使用 getter/setter(s) 发布您的属性,这是一个很好的做法,因此更好):

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(new File("target/javabook.json"), javabook);

It will produce human-readable output also, in this case JSON:

它也会产生人类可读的输出,在这种情况下是 JSON:

{"name":"Java unleashed","author":"someone","nop":1032,"price":450}

Using JSON approach you don't need to override toString methods as it will print all your fields but it's heavier in terms of performance, so for debugging use first method.

使用 JSON 方法您不需要覆盖 toString 方法,因为它会打印您的所有字段,但它在性能方面更重,因此对于调试使用第一种方法。

Hope this helps,

希望这可以帮助,

回答by Steve P.

It really depends on what you need the file to do. If you don't want to use the objects' toString()representations, you need to extract the content of each object, and come up with a delimiter, and use that delimiter to separate your data (book(s)). Note, you'd need a different delimiter to separate the data in each object. You can standardize how you write to the file, so that individual elements are easily retrieved. If you can come up with a delimiter, you can read in the data for one bookas a Stringand use split()to put each attribute into an array slot. If this is just for people to read, you can do something similar, but formatted nicely, so people know what they're actually reading. The object's toString()may be good for that:

这实际上取决于您需要该文件做什么。如果您不想使用对象的toString()表示,则需要提取每个对象的内容,并提出一个分隔符,并使用该分隔符分隔您的数据 ( book(s))。请注意,您需要一个不同的分隔符来分隔每个对象中的数据。您可以标准化写入文件的方式,以便轻松检索各个元素。如果你能想出一个分隔符,你可以读入一个book作为 a的数据,String并用于split()将每个属性放入一个数组槽中。如果这只是供人们阅读,你可以做一些类似的事情,但格式很好,所以人们知道他们实际上在阅读什么。该对象toString()可能对此有好处:

For reference, here's a toString()for your object:

作为参考,这是toString()您的对象:

    public String toString()
    {
         return name + " " + author + " " + price; 
    }

That was just an example, but if you put that in your book class and then attempt to print a book object, you'll get its name author priceas the printout.

这只是一个例子,但如果你把它放在你的书类中,然后尝试打印一个书对象,你会得到它name author price作为打印输出。

Also, you should use constructors/methods to assign values to your object's instance members, which should be private.

此外,您应该使用构造函数/方法将值分配给对象的实例成员,应该是private.

Ideally, I think you should use xml for your serialization; see XStream.

理想情况下,我认为您应该使用 xml 进行序列化;见XStream

回答by Evgeniy Dorofeev

You can serialize / desirialize your class instances as XML with JAXB or JavaBeans. In both cases you need to prepare your class - to use annotations or setters / getters.

您可以使用 JAXB 或 JavaBeans 将类实例序列化/反序列化为 XML。在这两种情况下,您都需要准备您的课程 - 使用注释或 setter/getter。