File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes transient I.0 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "transient I.0" Watch "transient I.0" New topic
Author

transient I.0

Michael Lin
Ranch Hand

Joined: Dec 04, 2000
Posts: 31
//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

Joined: Jun 13, 2000
Posts: 3340
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.

I Hope This Helps
Carl Trusiak, SCJP2, SCWCD
Zheng Huang
Ranch Hand

Joined: Dec 20, 2000
Posts: 49
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);
}
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: transient I.0
 
Similar Threads
TransientWriter
ob. serialization
transient
transient Variable
transient and Externalizable