-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReadObjectFromFile.java
68 lines (57 loc) · 1.71 KB
/
ReadObjectFromFile.java
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
package com.javamultiplex.filehandling;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StreamCorruptedException;
import java.util.Scanner;
public class ReadObjectFromFile {
public static void main(String[] args) throws IOException {
Scanner input = null;
ObjectInputStream ois = null;
FileInputStream fis = null;
try {
input = new Scanner(System.in);
System.out.println("Enter file name with extension : ");
String fileName = input.nextLine();
if (isValidFileName(fileName)) {
File file = new File(fileName);
if (file.exists()) {
fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
//Reading object from file.
Student student = (Student) ois.readObject();
System.out.println("---Student Information---");
System.out.println("Name : " + student.getName());
System.out.println("Age : " + student.getAge());
} else {
System.out.println("File not exists in current directory.");
}
} else {
System.out.println("File name is invalid.");
}
} catch (ClassNotFoundException exception) {
System.out.println(exception.getMessage());
} catch (StreamCorruptedException exception) {
System.out.println("Object is not present in given file.");
} finally {
if (input != null) {
input.close();
}
if (ois != null) {
ois.close();
}
if (fis != null) {
fis.close();
}
}
}
private static boolean isValidFileName(String fileName) {
String pattern = "^.+\\..+$";
boolean result = false;
if (fileName.matches(pattern)) {
result = true;
}
return result;
}
}