63 lines
1.7 KiB
Java
Raw Normal View History

2015-11-03 12:00:44 -08:00
// serialization/Logon.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// Demonstrates the "transient" keyword
2015-06-15 17:47:35 -07:00
import java.util.concurrent.*;
import java.io.*;
import java.util.*;
2017-01-22 16:48:11 -08:00
import onjava.Nap;
2015-06-15 17:47:35 -07:00
public class Logon implements Serializable {
private Date date = new Date();
private String username;
private transient String password;
public Logon(String name, String pwd) {
username = name;
password = pwd;
}
@Override
public String toString() {
2017-01-22 16:48:11 -08:00
return "logon info: \n username: " +
username + "\n date: " + date +
"\n password: " + password;
2015-06-15 17:47:35 -07:00
}
2017-01-22 16:48:11 -08:00
public static void main(String[] args) {
2015-06-15 17:47:35 -07:00
Logon a = new Logon("Hulk", "myLittlePony");
2015-11-03 12:00:44 -08:00
System.out.println("logon a = " + a);
try(
2017-01-22 16:48:11 -08:00
ObjectOutputStream o =
new ObjectOutputStream(
new FileOutputStream("Logon.dat"))
) {
2015-06-15 17:47:35 -07:00
o.writeObject(a);
2017-01-22 16:48:11 -08:00
} catch(IOException e) {
throw new RuntimeException(e);
2015-06-15 17:47:35 -07:00
}
2017-01-22 16:48:11 -08:00
new Nap(1);
2015-06-15 17:47:35 -07:00
// Now get them back:
try(
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("Logon.dat"))
) {
2015-12-15 11:47:04 -08:00
System.out.println(
"Recovering object at " + new Date());
a = (Logon)in.readObject();
2017-01-22 16:48:11 -08:00
} catch(IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
2015-12-15 11:47:04 -08:00
}
2015-11-03 12:00:44 -08:00
System.out.println("logon a = " + a);
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
logon a = logon info:
username: Hulk
date: Tue May 02 15:23:47 MDT 2017
2015-06-15 17:47:35 -07:00
password: myLittlePony
Recovering object at Tue May 02 15:23:48 MDT 2017
2015-06-15 17:47:35 -07:00
logon a = logon info:
username: Hulk
date: Tue May 02 15:23:47 MDT 2017
2015-06-15 17:47:35 -07:00
password: null
2015-09-07 11:44:36 -06:00
*/