forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectOutputInputStreamExampleTest.java
More file actions
53 lines (46 loc) · 1.33 KB
/
ObjectOutputInputStreamExampleTest.java
File metadata and controls
53 lines (46 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.examplehub.basics.io;
import static org.junit.jupiter.api.Assertions.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
class User implements Serializable {
// @Serial TODO
private static final long serialVersionUID = 100L;
private final String username;
private final String password;
private final int age;
public User(String username, String password, int age) {
this.username = username;
this.password = password;
this.age = age;
}
@Override
public String toString() {
return "User{"
+ "username='"
+ username
+ '\''
+ ", password='"
+ password
+ '\''
+ ", age="
+ age
+ '}';
}
}
class ObjectOutputInputStreamExampleTest {
@Test
void testWriteRead() throws IOException, ClassNotFoundException {
User user = new User("root", "112233", 25);
String filename = "user.db";
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
oos.writeObject(user);
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
User readUser = (User) ois.readObject();
assertEquals(user.toString(), readUser.toString());
}
assertTrue(Files.deleteIfExists(Paths.get(filename)));
}
}