Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. class User implements Serializable{
  2.  
  3. public User(String username, String password) {
  4. this.username=username;
  5. this.password=password;
  6. }
  7.  
  8. private static final long serialVersionUID = 1L;
  9. String username;
  10. String password;
  11.  
  12. }
  13.  
  14. public class SerializableExample {
  15.  
  16. public static void main(String[] args) {
  17. User user = new User("userB","passwordB");
  18.  
  19. String filename = "E:\Proj-docs\userFile.txt";
  20.  
  21. FileOutputStream file;
  22. try {
  23. file = new FileOutputStream(filename);
  24. ObjectOutputStream out = new ObjectOutputStream(file);
  25.  
  26. out.writeObject(user);
  27.  
  28. out.close();
  29. file.close();
  30. } catch (IOException e) {
  31. e.printStackTrace();
  32. }
  33.  
  34. User user2=null;
  35.  
  36. try {
  37. FileInputStream file2 = new FileInputStream(filename);
  38. ObjectInputStream in = new ObjectInputStream(file2);
  39.  
  40.  
  41. user2= (User) in.readObject();
  42.  
  43.  
  44. Optional checkNull = Optional.ofNullable(user2);
  45. if(checkNull.isPresent()) {
  46. System.out.println(user2.username + " "+user2.password);
  47.  
  48. }else {
  49. System.out.println("Null Object");
  50. }
  51.  
  52. }catch(IOException | ClassNotFoundException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56.  
  57. }
  58.  
  59. public class SerializableExample {
  60.  
  61. public static void main(String[] args) {
  62. User user = new User("userD","passwordD");
  63. String filename = "E:\Proj-docs\userFile.txt";
  64.  
  65. FileOutputStream file;
  66. try {
  67. file = new FileOutputStream(filename);
  68. ObjectOutputStream out = new ObjectOutputStream(file);
  69.  
  70. out.writeObject(user);
  71. out.close();
  72. file.close();
  73. :
  74. :
  75. :
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement