Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions Java/BasicSerializationExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* Created by Руслан on 30.05.2017.
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;


public class BasicSerializationExample {
static final String file = "user.txt";

static void serialize(User user) {
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream outputStream = new ObjectOutputStream(fos);
outputStream.writeObject(user);
outputStream.close();
} catch (IOException ex) {
System.err.println(ex);
}
}

static User deserialize() {
User savedUser = null;

try {
FileInputStream fis = new FileInputStream(file);
ObjectInputStream inputStream = new ObjectInputStream(fis);
savedUser = (User) inputStream.readObject();
inputStream.close();
} catch (IOException | ClassNotFoundException ex) {
System.err.println(ex);
}

return savedUser;
}

public static void main(String[] args) {
String username = "ruslan";
String email = "ruslankobrin@gmail.com";
String password = "pass";
Date birthDay = new Date();
int age = 30;

User newUser = new User(username, email, password, birthDay, age);

serialize(newUser);

User deseriaUser = deserialize();

if (deseriaUser != null) {
deseriaUser.printInfo();
}
}
}
35 changes: 35 additions & 0 deletions Java/User.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* Created by Руслан on 30.05.2017.
*/
import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {


private String username;
private String email;
private String password;
private Date birthday;
private int age;

public User(String username, String email, String password, Date birthday,
int age) {
this.username = username;
this.email = email;
this.password = password;
this.birthday = birthday;
this.age = age;
}

public void printInfo() {
System.out.println("username: " + username);
System.out.println("email: " + email);
System.out.println("password: " + password);
System.out.println("birthday: " + birthday);
System.out.println("age: " + age);
}

// getters and setters

}