Experiment 2.
Student Name: Nitesh UID: 21BCS5320
Branch: BE-CSE Section/Group:SC_907/ B
Semester: 6 Date of Performance:06-03-
2024 Subject Name: Java Lab
Subject Code:21CSH-319
1. Aim: Create a menu based Java application with the following options.1. Add an
[Link] [Link] If option 1 is selected, the application should gather details of
the employee like employee name, employee id, designation and salary and store it in a file. If
option 2 is selected, the application should display all the employee details. If option 3 is
selected the application should exit.
2. Objective:
• To learn about concept of File Handling in java.
• To learn about LinkedList, Exception Handling in java.
3. Algo. /Approach and output:
import [Link].*;
import [Link].*;
class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private int id; private String name; private int
age;
private double salary;
public Employee(int id, String name, int age, double salary) {
[Link] = id;
[Link] = name;
[Link] = age; [Link]
= salary;
}
@Override public String toString() { return
id + " " + name + " " + age + " " + salary;
}
}
public class emp2_4 { private static final String FILE_NAME =
"employee_data.txt"; private static final Scanner scanner = new
Scanner([Link]); private static final List<Employee> employees
= new ArrayList<>();
public static void main(String[] args) {
loadDataFromFile();
while (true) {
[Link]("\nMain Menu");
[Link]("1. Add an Employee");
[Link]("2. Display All");
[Link]("3. Exit");
[Link]("Enter your choice: ");
int choice = [Link]();
[Link](); // Consume newline
switch (choice)
{
case 1:
addEmployee();
break; case 2:
displayAllEmployees();
break; case 3:
saveDataToFile();
[Link]("Exiting the System"); return;
default:
[Link]("Invalid choice!");
}
}
}
private static void addEmployee() {
[Link]("Enter Employee ID: "); int id
= [Link]();
[Link](); // Consume newline
[Link]("Enter Employee Name: ");
String name = [Link]();
[Link]("Enter Employee Age: "); int age
= [Link]();
[Link]("Enter Employee Salary: ");
double salary = [Link]();
[Link](new Employee(id, name, age, salary));
[Link]("Employee added successfully.");
}
private static void displayAllEmployees() {
[Link]("----Report-----"); for
(Employee emp : employees) { [Link](emp);
}
[Link]("----End of Report-----");
}
private static void saveDataToFile() {
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(FILE_NAME))) {
[Link](employees);
[Link]("Data saved to file: " + FILE_NAME);
} catch (IOException e) { [Link]();
}
}
@SuppressWarnings("unchecked") private
static void loadDataFromFile() { File file
= new File(FILE_NAME);
if ([Link]()) {
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream(FILE_NAME))) {
[Link]((List<Employee>) [Link]());
} catch (IOException | ClassNotFoundException e) {
[Link]();
}
}
}
}
Output:-