开发者

I have written an object to an java file i/o got junk data in that file [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I have created an file in java which has object written in that file file has an text extension but got an junk character.Any tips,program or tutorial available for that Please Help.

There is an Package including Bean file

package Packageit;

import java.io.*;



public class Object1 implements Serializable
{
private String name;
private String Account;
private String City;




public void setName(String name)
{
   this.name=name;
}

public String getName()
{
 return name;
}

public void setAccount(String Account)
{
this.Account=Account;
}
public String getAccount()
{
 return Account;
}
public void setCity(String city)
{
 this.City=City;
}
public String getCity()
{
 return City;
}

}

and calling of that program is here

import java.io.*;
import Packageit.*;

public class FilterFlush {
public static void main (String args[])throws IOException
{   Object1 obj = new Object1();
    obj.setName("Girish");
    obj.setAccount("3456");
    obj.setCity("Ahmedabad");
        FileOutputStream f =new FileOutputStream("Tmp.txt");
    ObjectOutputStream ob =new ObjectOutputStream (f);
        ob.writeObject(obj);
        ob.flush();   
开发者_Go百科

}


}

here i got an junk data in the output file like

Ԁ牳ᄀ慐正条楥⹴扏敪瑣쀱늄㶔楚˱̀L䄇捣畯瑮t䰒慪慶氯湡⽧瑓楲杮䰻Ѐ楃祴q~䰁Ѐ慮敭q~码瑰Ѐ㐳㘵瑰؀楇楲桳

please help for solving that junk data

thanks in advance


The problem is that ObjectOutputStream uses a binary encoding for writing objects. If you want a somewhat readable version of the object, you can use XMLEncoder. This will give you an xml representation of the fields in your object.

Object1 obj = new Object1();
obj.setName("Girish");
obj.setAccount("3456");
obj.setCity("Ahmedabad");
    FileOutputStream f =new FileOutputStream("Tmp.txt");
XMLEncoder ob =new XMLEncoder (f);
    ob.writeObject(obj);
    ob.flush();   

If you want a truly human readable version of the object, then you should override the toString() method and combine the attributes into a meaningful string.

...
public String getCity()
{
 return City;
}

@Override
public String toString() 
{
    return Account + " for " + Name + " in " + City;
}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜