3

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

    }
}
4

5 回答 5

6

You could serialize it as XML by using JAXB or 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.

于 2013-05-29T14:57:55.427 回答
5

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

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

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();
        }
    }
}
于 2013-05-29T14:58:42.477 回答
2

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).

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

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.

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

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

It will produce human-readable output also, in this case 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.

Hope this helps,

于 2018-08-05T06:38:40.987 回答
1

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 book as a String and 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:

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

    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 price as the printout.

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

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

于 2013-05-29T15:00:08.680 回答
0

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.

于 2013-05-29T15:05:53.757 回答