Below is a program that should deserialize the record of employees. It does deserialize the first record but it does not deserialize the other records added by the user.
import java.io.*;
import java.util.*;
public class Employee implements Serializable {
private Object name;
private Object address;
private Object ssn;
private Object eadd;
private Object number;
private void writeObject(ObjectOutputStream os) throws IOException {
os.defaultWriteObject();
}
private void readObject (ObjectInputStream is) throws IOException, ClassNotFoundException {
is.defaultReadObject();
}
public static void addEmployee() {
try {
Employee e = new Employee();
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
FileOutputStream fileOut = new FileOutputStream("employee.ser", true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
System.out.println("Name: ");
e.name = buffer.readLine();
System.out.println("Address: ");
e.address = buffer.readLine();
System.out.println("SSN: ");
e.ssn = buffer.readLine();
System.out.println("Email: ");
e.eadd = buffer.readLine();
System.out.println("Number: ");
e.number = buffer.readLine();
out.writeObject(e +"#");
out.close();
fileOut.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void deserializeAll() throws ClassNotFoundException {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.ssn);
System.out.println("Email: " + e.eadd);
System.out.println("Number: " + e.number);
}
catch (IOException e1) {
e1.printStackTrace();
}
}
public static void main(String[] args) throws ClassNotFoundException {
int choice;
Scanner input = new Scanner (System.in);
do {
System.out.println("[1] Add an employee.");
System.out.println("[2] Deserialize all.");
choice = input.nextInt();
switch (choice) {
case 1: addEmployee(); break;
case 2: deserializeAll(); break;
default: System.exit(0);
}
} while (choice != 3);
}
}
The # is the delimeter per record.
You can't append to an ObjectOutputStream. Once you have closed it you cannot add to it.
Instead you either need to re-write the entire file or use a different file format (one which allow appending of data)
BTW: This doesn't write the Object
out.writeObject(e +"#");
It writes the e.toString() + "#" which is a String when you deserialize it, not the original object.
I would make your field types String instead of Object.
And I would delete your writeObject and readObject methods as they don't do anything.
Related
I have this in the Class: public static ArrayList<String> studentInfo = new ArrayList<String>();I created a method CreateStudent() that basically allows the user to create a student using Scanner, the DisplayStudent() uses ObjectInputStream to open the file and read the data. Now, when the users creates a student, it stores the data into an ArrayList using studentInfo.add(), the idea is that the EditStudent() access the data added into the ArrayList with the info added in CreateStudent() Is there a way to access that list from another method?I would appreciate any ideas, here is my code:
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.io.*;
import java.lang.ClassNotFoundException;
public class MidTermProject extends ObjectOutputStream {
private boolean append;
private boolean initialized;
private DataOutputStream dout;
static AtomicInteger idGenerator = new AtomicInteger(0001);
static int id;
public static String FullName;
public static String address;
public static String city;
public static String state;
public static String className;
public static String instructor;
public static String department;
public static String classNumber;
public static String courseNumber;
public static String year;
public static String semester;
public static String grade;
public static String studentID;
public static String courseID;
public static String enrollmentID;
public static ArrayList<String> studentInfo = new ArrayList<String>();
Scanner keyboard = new Scanner(System.in);
protected MidTermProject(boolean append) throws IOException, SecurityException {
super();
this.append = append;
this.initialized = true;
}
public MidTermProject(OutputStream out, boolean append) throws IOException {
super(out);
this.append = append;
this.initialized = true;
this.dout = new DataOutputStream(out);
this.writeStreamHeader();
}
#Override
protected void writeStreamHeader() throws IOException {
if (!this.initialized || this.append) return;
if (dout != null) {
dout.writeShort(STREAM_MAGIC);
dout.writeShort(STREAM_VERSION);
}
}
public static int getId() {
return id;
}
///Create Student Method
public static void CreateStudent() throws IOException {
File file = new File("StudentInfo.dat");
boolean append = file.exists();
Scanner keyboard = new Scanner(System.in);
try (
FileOutputStream fout = new FileOutputStream(file, append);
MidTermProject oout = new MidTermProject(fout, append);
) {
id = idGenerator.getAndIncrement();
studentID = Integer.toString(getId());
oout.writeObject("Student ID: " + studentID);
System.out.print("\nPlease enter your information bellow.\n" + "\nFull Name: ");
FullName = keyboard.nextLine();
oout.writeObject("Full Name: " + FullName);
System.out.print("Address: ");
address = keyboard.nextLine();
oout.writeObject("Address: " + address);
System.out.print("City: ");
city = keyboard.nextLine();
oout.writeObject("City: " + city);
System.out.print("State: ");
state = keyboard.nextLine();
oout.writeObject("State: " + state + "\n");
studentInfo.add(studentID);
studentInfo.add(FullName);
studentInfo.add(address);
studentInfo.add(city);
studentInfo.add(state);
oout.close();
System.out.println("Done!\n");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
///Edit Student Method
public static void EditStudent() throws IOException {
String editName;
String editaddress;
String editCity;
String editState;
int editID;
String editStudent;
boolean endOfFile = false;
Scanner keyboard = new Scanner(System.in);
System.out.print(studentInfo);
System.out.print("Enter the ID of the student you would like to edit: ");
editID = keyboard.nextInt();
String editingID = Integer.toString(editID);
FileInputStream fstream = new FileInputStream("StudentInfo.dat");
ObjectInputStream inputFile = new ObjectInputStream(fstream);
File file = new File("StudentInfo.dat");
boolean append = file.exists();
while(!endOfFile)
{
try
{
FileOutputStream fout = new FileOutputStream(file, append);
MidTermProject oout = new MidTermProject(fout, append);
editStudent = (String) inputFile.readObject();
if(editingID == oout.studentID) {
System.out.print("\nPlease enter NEW information bellow.\n" + "\nFull Name: ");
editName = keyboard.nextLine();
oout.writeObject("Full Name: " + editName);
System.out.print("Address: ");
editaddress = keyboard.nextLine();
oout.writeObject(editaddress);
System.out.print("City: ");
editCity = keyboard.nextLine();
oout.writeObject(editCity);
System.out.print("State: ");
editState = keyboard.nextLine();
oout.writeObject(editState);
oout.close();
System.out.print("Successfully Edited");
} else {
System.out.print("Error");
}
}
catch (EOFException | ClassNotFoundException e)
{
endOfFile = true;
}
}
}
Display Student Method
public static void DisplayStudent() throws IOException {
FileInputStream fstream = new FileInputStream("StudentInfo.dat");
ObjectInputStream inputFile = new ObjectInputStream(fstream);
String student;
boolean endOfFile = false;
while(!endOfFile)
{
try
{
student = (String) inputFile.readObject();
System.out.print(student + "\n");
}
catch (EOFException | ClassNotFoundException e)
{
endOfFile = true;
}
}
System.out.println("\nDone");
inputFile.close();
}
i have a problem in my java exercise.
i need to print a multiply contact information to a file, but when i print more then 1 contact, only 1 contact is displayed in the file..
i tried to debug that but i cant find any mistake
i will put the code of my classes here:
This is Demo Class which i run the code from
public class Demo {
public static void main(String[] args) {
System.out.println("Insert number of Contacts:");
Scanner scanner = new Scanner(System.in);
int val = scanner.nextInt();
Contact[] contacts = new Contact[val];
for(int i = 0 ; i < val; i++) {
System.out.println("Contact #"+(i+1));
System.out.print("Owner: \n");
String owner = scanner.next();
System.out.print("Phone number: \n");
String phoneNum = scanner.next();
System.out.print("Please Select Group:\n"
+ "1 For FRIENDS,\n" +
"2 For FAMILY,\n" +
"3 For WORK,\n" +
"4 For OTHERS");
int enumNum = scanner.nextInt();
Group group;
switch(enumNum) {
case 1:
group=Group.FRIENDS;
break;
case 2:
group=Group.FAMILY;
break;
case 3:
group=Group.WORK;
break;
default:
group=Group.OTHERS;
}//switch end
contacts[i] = new Contact(owner,phoneNum,group);
}//loop end
System.out.println("Insert File name");
String fileName = scanner.next();
File f=null;
for(int i = 0 ; i < val; i++) {
if(i==0) {
f = new File(fileName);
contacts[0].Save(fileName);
}
else {
contacts[i].Save(f);
}
}
}
}
This is Contact Class:
enum Group {
FRIENDS,
FAMILY,
WORK,
OTHERS
};
public class Contact {
private String phoneNumber,owner;
private Group group;
PrintWriter pw = null;
public Contact(String owner ,String phoneNumber,Group group) {
setPhoneNumber(phoneNumber);
setOwner(owner);
setGroup(group);
}
public Contact(String fileName) {
File file = new File(fileName+".txt");
try {
Scanner scanner = new Scanner(file);
phoneNumber=scanner.nextLine();
owner=scanner.nextLine();
String str=scanner.nextLine();
group = Group.valueOf(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
public Contact(File file) {
try {
Scanner scanner = new Scanner(file);
phoneNumber=scanner.nextLine();
owner=scanner.nextLine();
String str=scanner.nextLine();
group = Group.valueOf(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public void Save(String fileName) {
File f = new File(fileName+".txt");
try {
if(f.createNewFile()) {
System.out.println("File created");
pw = new PrintWriter(f); //יצירת מדפסת לקובץ
pw.println(phoneNumber+"\n"+owner+"\n"+group+"\n\n\n");
}
} catch (IOException e) {
e.printStackTrace();
}
pw.close();
}
public void Save(File f) {
PrintWriter pw=null;
try {
pw = new PrintWriter(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.println(phoneNumber+"\n"+owner+"\n"+group);
pw.close();
}
public String toString() {
return phoneNumber+"\n"+owner+"\n"+group;
}
}
Every time you create PrintWriter the file is being overwritten. Since you create a new PrintWriter for each contact, the file contains only the last contact information. What you should do is to create PrintWriter only once and use it for all contacts.
Firstly, let's create a new save method with such signature:
public void save(PrintWriter writer)
I have also used the lowercase name of the method due to Java naming convention.
Now the implementation of save method will look like this:
writer.println(phoneNumber);
writer.println(owner);
writer.println(group + "\n\n\n");
Then we should replace the usage of Save method with the new one. Here is your code:
String fileName = scanner.next();
File f = null;
for (int i = 0; i < val; i++) {
if(i == 0) {
f = new File(fileName);
contacts[0].Save(fileName);
} else {
contacts[i].Save(f);
}
}
In order to fix the issue we can change it like this:
String fileName = scanner.next();
File file = new File(fileName);
try (PrintWriter writer = new PrintWriter(file)) {
for (int i = 0; i < val; i++) {
contacts[i].save(writer);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I have also used try-with-resources which closes the PrintWriter automatically.
From the Javadoc of the constructor of PrintWriter:
public PrintWriter(File file)
Parameters: file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
In the Save function you create a PrintWriter everytime. So everytime the file is truncated, and then you lose the contact you saved before.
Since File I/O classes in java use Decorator Design pattern, you can use a FileWriter to take advantage of appending to a file. So you can use this code for Save() method :
public void Save(String fileName) {
File f = new File(fileName+".txt");
try {
//System.out.println("File created"); You don't need to create new file.
FileWriter fw=new FileWriter(f,true):// second argument enables append mode
pw = new PrintWriter(fw); //יצירת מדפסת לקובץ
pw.println(phoneNumber+"\n"+owner+"\n"+group+"\n\n\n");
} catch (IOException e) {
e.printStackTrace();
}
pw.close();
}
I made a class called Subject. The class consists of these lines:
class Subject {
int serial;
Double credit, gpa, tgpa = 0.0;
public Subject(int serial, Double credit, Double gpa, Double tgpa) {
this.serial = serial;
this.credit = credit;
this.gpa = gpa;
this.tgpa = tgpa;
}
public int getSerial() {
return serial;
}
public void setSerial(int serial) {
this.serial = serial;
}
public Double getCredit() {
return credit;
}
public void setCredit(Double credit) {
this.credit = credit;
}
public Double getGpa() {
return gpa;
}
public void setGpa(Double gpa) {
this.gpa = gpa;
}
public Double getTgpa() {
return tgpa;
}
public void setTgpa(Double tgpa) {
this.tgpa = tgpa;
}
}
I'm trying to create two methods for Saving the ArrayList of Subject into a file and Reopen it as an ArrayList of Subject.
Any solution?
You could use serialization and deserialization to write it into a file:
try (FileOutputStream fos = new FileOutputStream("serializedObject.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(yourArrayList);
}
Then you can read it again and cast it:
ObjectInputStream ois =
new ObjectInputStream(new FileInputStream("serializedObject.txt"));
//Gets the object
ois.readObject();
A small example from:Java serialization
A very small note with these examples: I kept the original example.
Please always close your files and streams in the finally clause!
Create object:
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck() {
System.out.println("Mailing a check to " + name + " " + address);
}
}
Write object to file:
import java.io.*;
public class SerializeDemo {
public static void main(String [] args) {
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
}catch(IOException i) {
i.printStackTrace();
}
}
}
To get the list back:
import java.io.*;
public class DeserializeDemo {
public static void main(String [] args) {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i) {
i.printStackTrace();
return;
}catch(ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
You can either use Java Serialization and Deserialization or Jackson API to store and retrieve .
This is a simple example where I'm trying to write and read Objects stored in ArrayList to/from file.
Writing file is working. Reading file is working only for first Object in my ArrayList. How should I make this into a loop?
I tried with something like:
`while(ois !=null) {
Person result = (Person) ois.readObject();
persons.add(result);
}
but it's not working.
Here is full test code:
public class Data {
static ArrayList<Person> persons = new ArrayList<Person>();
public static void savePersons() throws IOException{
FileOutputStream fout = null;
ObjectOutputStream oos = null;
/** Make 5 'Person' object for examle */
for(int i = 0; i<5; i++){
Person personTest = new Person("name", "surname", "email", "1234567890");
persons.add(personTest);
}
try{
fout = new FileOutputStream("C:\\data.dat", true);
oos = new ObjectOutputStream(fout);
oos.writeObject(persons);
System.out.println("Saving '" +persons.size()+ "' Object to Array");
System.out.println("persons.size() = " +persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR");
} finally {
if(oos != null){
oos.close();
}
}
}
public static void loadPersons() throws IOException{
FileInputStream fis = null;
ObjectInputStream ois = null;
/** Clean 'persons' array for TEST of load data*/
persons.removeAll(persons);
try {
fis = new FileInputStream("C:\\data.dat");
ois = new ObjectInputStream(fis);
Person result = (Person) ois.readObject();
persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" +persons.size()+ "' Object from Array");
System.out.println("persons.size() = " +persons.size());
System.out.println("loadPersons() = OK");
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR");
} finally {
if(ois != null){
ois .close();
}
}
}
}
Person class:
public class Person implements Serializable {
private String name;
private String surname;
private String mail;
private String telephone;
Person person;
public Person(String n, String s, String m, String t){
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}}
Main class:
public class Test {
public static void main(String[] args) {
Data.savePersons();
Data.loadPersons();
}}
Here you go... please take note of the following:
YES, Chetan Jadhav CD's suggestion WORKS. B
Use an IDE like Eclipse to help you debug your code and make your life easier.
Be clear about what your error is (show stack trace, etc..) Note the modification to your catch clause that prints:
System.out.println("Saving ERROR: " + ex.getMessage());
Put all your code in one file before you ask for help to make everyone's life easier.
Make each 'Person' at least someone unique by numbering them with your index Use .ser for a serializable file, rather than .dat
import java.util.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class Data {
private static final String SER_FILE = "C:\\view\\data.ser";
static List<Person> persons = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
Data.savePersons();
Data.loadPersons();
}
public static void savePersons() throws IOException {
/** Make 5 'Person' object for example */
for (int i = 0; i < 5; i++) {
Person personTest = new Person("name" + i, "surname" + i, "email" +i, "1234567890-" +i);
persons.add(personTest);
}
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SER_FILE, true));) {
oos.writeObject(persons);
System.out.println("Saving '" + persons.size() + "' Object to Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR: " + ex.getMessage());
}
}
public static void loadPersons() throws IOException {
/** Clean 'persons' array for TEST of load data */
persons.removeAll(persons);
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SER_FILE));){
persons = (List<Person>) ois.readObject();
//persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" + persons.size() + "' Object from Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("loadPersons() = OK");
persons.stream().forEach(System.out::println);
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR: " + e.getMessage());
}
}
}
class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String surname;
private String mail;
private String telephone;
public Person(String n, String s, String m, String t) {
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}
#Override
public String toString() {
return "Person [name=" + name + ", surname=" + surname + ", mail=" + mail + ", telephone=" + telephone + "]";
}
}
I am just trying to output a previously created ArrayList to serialise it for future storage.
but when I attmept to do so I get the runTime error "notSerialisableException: Department.
Is their a speicial way of serializing an arrayList??
Would someone be able to tell me why I may be getting this error.
This is the code:
import java.awt.*;
import java.util.*;
import java.io.*;
import java.io.Serializable;
public class tester1ArrayListObjectSave
{
private ArrayList <Department> allDeps = new ArrayList<Department>();
private int choice = 0;
private String name;
private String loc;
Department theDepartment;
Scanner scan;
public static void main(String[] args)
{
new tester1ArrayListObjectSave();
}
public tester1ArrayListObjectSave()
{
scan = new Scanner(System.in);
options();
}
public void options()
{
System.out.println("wadya wanna do");
System.out.println("1. create a new department");
System.out.println("2. read from text file");
System.out.println("4. save it to system as a serializable file");
System.out.println(". read from text file");
System.out.println("3. to exit");
choice = scan.nextInt();
workOutOptions();
}
public void workOutOptions()
{
if (choice ==1)
{
createNewEmp();
}
else if (choice ==2)
{
try
{
readTextToSystem();
}
catch (IOException exc)
{
System.out.println("uh oh their was an error: "+exc);
}
}
else if (choice == 3)
{
System.exit(0);
}
else if (choice ==4)
{
try
{
createSerialisable();
}
catch (IOException exc)
{
System.out.println("sorry could not serialise data cause of this:"+exc);
}
}
else
{
System.out.println("do nothing");
}
}
public void createNewEmp()
{
System.out.println("What is the name");
name = scan.next();
System.out.println("what is the chaps loc");
loc = scan.next();
try
{
saveToSystem();
}
catch (IOException exc)
{
// do something here to deal with problems
}
theDepartment = new Department(name,loc);
allDeps.add(theDepartment);
options();
}
public void saveToSystem() throws IOException
{
FileOutputStream fos = new FileOutputStream( "backUp.txt", true );
PrintStream outFile = new PrintStream(fos);
System.out.println("added to system succesfully");
outFile.println(name);
outFile.println(loc);
outFile.close();
options();
}
public void readTextToSystem() throws IOException
{
Scanner inFile = new Scanner ( new File ("backUp.txt") );
while (inFile.hasNextLine())
{
name=inFile.nextLine();
System.out.println("this is the name: "+name);
loc = inFile.nextLine();
System.out.println("this is the location: "+loc);
Department dDepartment = new Department(name,loc);
allDeps.add(dDepartment);
options();
}
System.out.println(allDeps);
}
public void createSerialisable() throws IOException
{
FileOutputStream fileOut = new FileOutputStream("theBkup.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(allDeps);
options();
}
}
ArrayList isn't the problem; your Department object is.
You need to implement the Serializable interface in that object.