• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

transient I.0

 
Michael Lin
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//there is problem with this code, I can not fix it.
//can someone please help to explain it? Thanks!!
import java.io.*;
public class TransientWriter implements Externalizable
{

private transient String s = "Hope I can ever be persistant!";
public void writeExternal(ObjectOutput oOut) throws IOException
{
oOut.writeObject(s);
}

public void readExternal(ObjectInput oIn) throws IOException,
ClassNotFoundException
{
s=(String)oIn.readObject();
}
public String toString()
{
return s;
}
}
class K
{
public static void main(String args[]) throws IOException, ClassNotFoundException
{
TransientWriter tw = new TransientWriter();
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tw.out"));
out.writeObject(tw);
ObjectInputStream in = new ObjectInputStream(new FileInputStream("tw.out"));
TransientWriter tw2 = (TransientWriter) in.readObject();
System.out.println(tw2);
}
}
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You didn't say what your problem is but, you need to read the JLS on the use of the transient keyword. It prevents that data from being written to the object output stream!
Change your code to this and rerun it.

This should clear up the use of transient.
 
Zheng Huang
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use Serializable not Externalizable. see below.
import java.io.*;
public class TransientWriter implements Serializable // not Externalizable
{
private transient String s = "Hope I can ever be persistant!";

public void writeExternal(ObjectOutput oOut) throws IOException
{
oOut.writeObject(s);
}
public void readExternal(ObjectInput oIn) throws IOException,
ClassNotFoundException
{
s=(String)oIn.readObject();
}
public String toString()
{
return s;
}
public static void main(String args[]) throws IOException, ClassNotFoundException
{
TransientWriter tw = new TransientWriter();
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tw.out"));
out.writeObject(tw);
ObjectInputStream in = new ObjectInputStream(new FileInputStream("tw.out"));
TransientWriter tw2 = (TransientWriter) in.readObject();
System.out.println(tw2.s);
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic