-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSerializeObj.java
More file actions
85 lines (73 loc) · 2.6 KB
/
SerializeObj.java
File metadata and controls
85 lines (73 loc) · 2.6 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package serialization;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Scanner;
public class SerializeObj {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int id = sc.nextInt();
sc.nextLine();
String name = sc.nextLine();
char section = 'a';
String school = "jnv dkl";
int marks = sc.nextInt();
SerialObject so = new SerialObject(id, name, section, marks, school);
// File f = new File("C:/Users/admin/codePractice/java_repo/core_java_from_scratch_studytonight/serial.txt");
// serialize
try {
String path = "C:/Users/admin/codePractice/java_repo/core_java_from_scratch_studytonight/serial.txt";
FileOutputStream fos = new FileOutputStream(path);
// write using byte stream
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(so);
// writes to file using character stream
// fos.write("ID,NAME,MARKS\n".getBytes());
// fos.write((so.getId()+","+so.getName()+","+so.getMarks()+"\n").getBytes());
fos.flush();
fos.close();
System.out.println("Complete.");
} catch (Exception e) {
e.printStackTrace();
}
// deserialize
// try{
// FileInputStream fis = new FileInputStream("C:/Users/admin/codePractice/java_repo/core_java_from_scratch_studytonight/serial.txt");
// ObjectInputStream ois = new ObjectInputStream(fis);
// SerialObject os = (SerialObject) ois.readObject();
// os.showInfo();
// }catch (Exception e){
// e.printStackTrace();
// }
}
}
class SerialObject implements Serializable {
static char section;
static String school;
private int id;
private String name;
private transient int marks;
public SerialObject(int id, String name, char section, int marks, String school) {
this.id = id;
this.name = name;
this.section = section;
this.marks = marks;
this.school = school;
}
public int getId(){
return this.id;
}
public String getName(){
return this.name;
}
public int getMarks(){
return this.marks;
}
public void showInfo() {
System.out.println("id: " + this.id);
System.out.println("name: " + this.name);
System.out.println("section: " + section);
System.out.println("marks: " + marks);
System.out.println("school: " + school);
}
}