Reading objects from a file and adding them to an array - java

I'm trying to read objects from a file then add them to an Array List of Ticket. But it's not working. May I please know where's the problem?
public void writeTicketToFile(Ticket ticket) {
try {
FileOutputStream fileOut = new FileOutputStream("tickets.txt");
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(ticket.toString());
objectOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void readTicketFromFile(){
ArrayList<Ticket> tickets = new ArrayList<Ticket>();
try {
FileInputStream fi = new FileInputStream(new File("tickets.txt"));
ObjectInputStream oi = new ObjectInputStream(fi);
Ticket ticket;
while (ticket=oi.readObject() != null){
tickets.add((Ticket)oi.readObject());
}
System.out.println(tickets);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

One of your main problems lies here:
while (ticket=oi.readObject() != null){
tickets.add((Ticket)oi.readObject());
}
Compare the fact that you're trying to read a Ticket object out of a file with the way you're writing the Ticket to the file:
objectOut.writeObject(ticket.toString());
As you can see, you're converting the Ticket to a String and writing the String to the file. Then when you try to read, you're trying to read a Ticket. Instead, you should read a String, and then convert the String into a Ticket in code.
If Ticket is serializable, you may instead just be able to remove .toString() from the write step, but I've never worked with object streams, so I can't say 100% if that will work.

There are a lot of issues here:
Make sure your Ticket implements Serializable interface for writing/reading objects from/to file as in this simple example:
public class Ticket implements Serializable{
private String name;
private LocalDateTime issued;
public Ticket() {
}
public Ticket(String name, LocalDateTime issued) {
this.name = name;
this.issued = issued;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the issued
*/
public LocalDateTime getIssued() {
return issued;
}
/**
* #param issued the issued to set
*/
public void setIssued(LocalDateTime issued) {
this.issued = issued;
}
}
Now pay attention to while writing tickets to a file to write them one at a time. You can achieve it by iterating thru your list of tickets and writing it one at a time, something like:
for (int i = 0; i < tickets.size(); i++) {
objectOut.writeObject(tickets.get(i));
}
Also, make sure to close your ObjectInputStream after reading as it will surely throw EOFException at the end, take a look at implementation of it in readTicketFromFile method.
public class SerializationAndDeserializationOfTicket {
public static void main(String[] args) {
List<Ticket> listOfTickets = new ArrayList<>();
listOfTickets.add(new Ticket("Concert 1", LocalDateTime.now()));
listOfTickets.add(new Ticket("Concert 2", LocalDateTime.now()));
listOfTickets.add(new Ticket("Concert 3", LocalDateTime.now()));
writeTicketToFile(listOfTickets);
readTicketFromFile();
}
public static void writeTicketToFile(List<Ticket> tickets) {
try {
FileOutputStream fileOut = new FileOutputStream("tickets.txt");
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
for (int i = 0; i < tickets.size(); i++) {
objectOut.writeObject(tickets.get(i));
}
objectOut.close();
} catch (IOException e) {
System.err.println("JVM reported an IO exception. Please, take a look.");
}
}
public static void readTicketFromFile() {
ArrayList<Ticket> tickets = new ArrayList<>();
try {
FileInputStream fi = new FileInputStream(new File("tickets.txt"));
ObjectInputStream oi = new ObjectInputStream(fi);
while (true) {
try {
Ticket ticket = (Ticket) oi.readObject();
tickets.add(ticket);
System.out.println(ticket.getName() + " " + ticket.getIssued());
} catch (EOFException ex) {
oi.close();
break;
}
}
} catch (IOException | ClassNotFoundException e) {
System.err.println("JVM reported an IO/ClassNotFound exception. Please, take a look.");
}
}

Just add the Ticket objects into an ArrayList and write the list (instead of each object one by one) as a single object. Then read the list from the file in your readTicketFromFile() method as :
ArrayList<Ticket> ticketsList = (ArrayList<Ticket>)oi.readObject();

Related

Serialized Object file is empty when program has no errors

I am not sure why file , BankAccount.ser is empty after successful run of below code. BankAccount.ser file is a class path resource. After successful run of SuccessfulSerializationTestDriver , BankAccount.ser is zero bytes on disk and has no contents.
public class SuccessfulSerializationTestDriver {
public static void main(String[] args) {
long accountNumber=12033456;
String bankName="SBI";
String branch="NOIDA";
SerializableBankAccount sBankAccount = new SerializableBankAccount();
sBankAccount.setAccountNumber(accountNumber);
sBankAccount.setBankName(bankName);
sBankAccount.setBranch(branch);
try(FileOutputStream fileOut =new FileOutputStream("BankAccount.ser")){
ObjectOutputStream out= new ObjectOutputStream(fileOut);
out.writeObject(sBankAccount);
out.flush();
out.close();
System.out.println("Bank Account is successfully serialized");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Serializable class is ,
public class SerializableBankAccount implements Serializable {
private static final long serialVersionUID = 1L;
private long accountNumber;
private String bankName;
private String branch;
public long getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(long accountNumber) {
this.accountNumber = accountNumber;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
#Override
public String toString(){
return accountNumber+","+bankName+","+branch;
}
}
EDIT : I wrote deserializer and I am getting object successfully - so it just seems a visibility issue. Somehow file is shown of zero bytes.
public class SuccessfulDeSerializationTestDriver {
public static void main(String[] args) {
SerializableBankAccount sBankAccount = null;
try(FileInputStream fileIn =new FileInputStream("BankAccount.ser")){
ObjectInputStream inStream= new ObjectInputStream(fileIn);
sBankAccount= (SerializableBankAccount) inStream.readObject();
inStream.close();
System.out.println("Successfully Deserialized Object is "+sBankAccount);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Successfully Deserialized Object is 12033456,SBI,NOIDA
If the file you're looking at is zero bytes, but it deserializes successfully, it sounds like the file is being created elsewhere. Perhaps specify the path explicitly when you create the file name for a start. The file with size 0, may be from an older run - delete that on disk, and see if it gets created again.
I am not able to recreate the problem you're having. When I run your code the BankAccount.ser file is created and is not empty. In fact I wrote a deserialization test to see if I could get the object back by reading the file and it works fine.
Here is the deserializing class in case you want it:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class DeserializationTestDriver {
public static void main(String[] args) {
try(FileInputStream fileInput =new FileInputStream("BankAccount.ser")){
ObjectInputStream input = new ObjectInputStream(fileInput);
SerializableBankAccount sBankAccount = (SerializableBankAccount) input.readObject();
input.close();
System.out.println("Bank Account is successfully deserialized: "+sBankAccount.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
I also added a toString method to your SerializableBankAccount:
#Override
public String toString() {
return "SerializableBankAccount [accountNumber=" + accountNumber
+ ", bankName=" + bankName + ", branch=" + branch + "]";
}
After running your serialization code and then running the above deserialization I get this output:
Bank Account is successfully deserialized: SerializableBankAccount [accountNumber=12033456, bankName=SBI, branch=NOIDA]
So clearly the code is fine, which means it has to be something to do with the environment. I suggest checking whether you're running the program with correct privileges, permissions, etc. It seems that something external to your code is preventing you from writing to the file. Either that or perhaps you're looking at the wrong file, verify you have the correct path and check the file creation and modification dates.

Java - Existence of method causing program to not work correctly

In my Java program, I have a class called Car, which is Serializable. I have another class called StaffCar which is a subclass of Car.
Then there a class called Fleet which essentially stores StaffCar objects in ArrayList<StaffCar> fleet.
I then have a class Main which consists of the main method which consists of a menu and a switch to handle menu options.
The problem I'm having is when I add a method in StaffCar, even if the method has nothing inside and the method isn't even called, one of the menu options which is 'Display all car information', stops working.
If I comment out this method, it starts working again.
The 'Display...' option calls printCars()from Fleet which has fleet loaded with StaffCar objects from the serialized file, it's like the existence of this method stops the file from even being read.
Snippet of Car
import java.util.ArrayList;
import java.io.*;
#SuppressWarnings("serial")
public class Car implements Serializable
{
//attributes for Car
String regNo;
String model;
int mileage;
//default constructor
public Car() throws CarException
{
try
{
setRegNo("??????");
setModel("Unknown");
setMileage(0);
}
catch (CarException c)
{
System.out.println(c.getMessage());
}
}
//setters
public void setRegNo(String regNo) throws CarException
{
if (regNo.isEmpty())
{
throw new CarException("\nInvalid registration number!\n");
}
this.regNo = regNo;
}
public void setModel(String model) throws CarException
{
if (model.isEmpty())
{
throw new CarException("\nModel can't be empty!\n");
}
this.model = model;
}
public void setMileage(int mileage) throws CarException
{
if (mileage < 0)
{
throw new CarException("\nInvalid mileage!");
}
this.mileage = mileage;
}
}
Snippet of StaffCar, where the problem is being caused
import java.util.ArrayList;
#SuppressWarnings("serial")
public class StaffCar extends Car
{
String staffName;
String availability;
public StaffCar() throws CarException
{
super();
try
{
setAvailability("Available");
setStaffName("");
}
catch (CarException c)
{
System.out.println(c.getMessage());
}
}
public void setStaffName(String staffName)
{
this.staffName = staffName;
}
public void setAvailability(String availability) throws CarException
{
if (availability != "Available" && availability != "Borrowed")
{
throw new CarException("\nInvalid borrow status!\n");
}
this.availability = availability;
}
//this method causing issues, even if empty
/*public void returnCar()
{
}*/
}
Snippet of Fleet class
import java.util.ArrayList;
import java.io.*;
public class Fleet
{
//declare container
ArrayList<StaffCar> fleet;
//container to hold regNos
ArrayList<String> regNumbers;
//create constructor
public Fleet()
{
fleet = new ArrayList<StaffCar>();
regNumbers = new ArrayList<String>();
}
//add method
public void addCar(StaffCar car)
{
fleet.add(car);
regNumbers.add(car.regNo);
}
//print all cars' details
public void printCars()
{
for (StaffCar car:fleet)
{
System.out.println(car);
}
}
public void saveAs(String fileName) throws CarException
{
FileOutputStream outputFile;
try
{
outputFile = new FileOutputStream(fileName);
}
catch (IOException io)
{
throw new CarException("\nCannot create " + fileName + "\n");
}
ObjectOutputStream fleetFile;
try
{
fleetFile = new ObjectOutputStream(outputFile);
fleetFile.writeObject(regNumbers);
fleetFile.writeObject(fleet);
fleetFile.close();
}
catch (FileNotFoundException e)
{
throw new CarException("\nCannot create " + fileName + "\n");
}
catch (IOException io)
{
throw new CarException("\nCannot write " + fileName + "\n");
}
}
#SuppressWarnings({ "unchecked", "resource" })
public void open(String fileName) throws CarException
{
FileInputStream inputFile;
try
{
inputFile = new FileInputStream(fileName);
}
catch (FileNotFoundException e)
{
throw new CarException("\nCannot open " + fileName + "\n");
}
ObjectInputStream fleetFile;
try
{
fleetFile = new ObjectInputStream(inputFile);
regNumbers = (ArrayList<String>)fleetFile.readObject();
fleet = (ArrayList<StaffCar>)fleetFile.readObject();
}
catch (IOException io)
{
throw new CarException("\nError reading from " + fileName + "\n");
}
catch (ClassNotFoundException e)
{
throw new CarException("\nError reading from " + fileName + "\n");
}
try
{
fleetFile.close();
}
catch (IOException io)
{
throw new CarException("\nCannot close " + fileName + "\n");
}
}
}
I apologise for what seems like me dumping a bunch of code to you, I know this is bad practice and I have tried to condense the code as much as I can, but I feel like this is all the relevant code to my problem.
Like I said, I don't understand why the simple addition of an empty method is causing this issue.
EDIT
Main class
public class Main
{
// new container
static Fleet fleet = new Fleet();
// initialise car object
static StaffCar car;
// programme loop variable
static boolean state = false;
String fileName;
public static void main(String[] args) throws CarException
{
start();
// programme loop
while (!state)
{
try
{
// menu option variable
String option;
//displays menu to user and takes in input
option = Console.askString("Menu:\n1 Add a car\n2 Display all car information\n3 Find a car\n4 Borrow a car\n5 Return a car\n6 Exit\n\n");
//removes white spaces
option = option.trim();
//switch to handle user request
switch (option)
{
//if option 1
case "1":
//call static add car method
addMethod();
break;
//if option 2
case "2":
//call static print car method
displayMethod();
break;
//..option 3
case "3":
//call static find car method
findMethod();
break;
//..option 4
case "4":
borrowMethod();
break;
case "5":
//returnMethod();
break;
case "6":
//call static quit method
quitMethod();
break;
default:
System.out.println();
System.out.println("Invalid option.");
System.out.println();
break;
}
}
catch (CarException c)
{
System.out.println(c.getMessage());
}
}
}
public static void start()
{
try
{
fleet.open("fleet.uwl");
}
catch (CarException e)
{
//System.out.println("\nFile not created yet!\n");
}
}
//static menu method to print cars
public static void displayMethod() throws CarException
{
System.out.println();
//call printCars method
fleet.printCars();
System.out.println();
}
}
You saved instances of StaffCar using serialization, then changed the StaffCar class, and are unable to read the saved StaffCar again.
That's because, if you don't specify a serialVersionUID in your class, the JVM computes one for you, based on the layout of the class (fields, methods, etc.). So, to temporarily fix your problem, examine the IOException thrown when reading the file, which should tell you what the serialVersionUID of the saved classes are, and add the following to your class:
private static final long serialVersionUID = XXXL;
where XXX is the serial version UID in the saved objects, which should be mentioned in the exception stack trace.
But really, you have these problems because you chose to use serialization for long term storage, which makes your code very hard to evolve. I wouldn't do that. Instead, I would choose a less fragile and easier to evolve format such as JSON or XML. Define what the file should contain, and generate a JSON/XML document containing this data. Then, whatever your future casses look like, as long as you still can parse JSON/XML, you'll be able to read the files and get the saved data.

Trying to save Custom Array of Objects Android

So I'm making a notepad application that logs date entered, a subject, and a body text field. When I hit my post button, everything appears properly in my ListView, but when I close the application and re-open it, only the date remains intact and the other two values are NULL. Below is the code I'm using.
public class LogList implements Serializable {
private String logDate;
private String logBody;
private String logSubject;
public LogList(String date, String LogBody, String LogSubject){
super();
this.logDate = date;
this.logBody = logBody;
this.logSubject = logSubject;
}
Back in my main class, I have my method that is supposed to save the three values into an ArrayList lts.
private void saveInFile(String subject_text, String date, String body_text ){
LogList lt = new LogList(date, subject_text, body_text);
lts.add(lt);
saveAllLogs();
}
Now if I change the order of the values in my new LogList, only the first one will be properly displayed after I close my app and reopen it. The following are my saveAllLogs method and my loadFromFile method.
private ArrayList<String> loadFromFile(){
ArrayList<String> logs = new ArrayList<String>();
try {
FileInputStream fis = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
while (true) {
LogList lt = (LogList) ois.readObject();
logs.add(lt.toString());
lts.add(lt);
}
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
catch (ClassNotFoundException e) { e.printStackTrace(); }
return logs;
}
private void saveAllLogs() {
try {
FileOutputStream fos = openFileOutput(FILENAME, 0);
ObjectOutputStream oos = new ObjectOutputStream(fos);
for (LogList lti : lts) {
oos.writeObject(lti);
}
fos.close();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
Any help would be greatly appreciated!
For one thing,
public LogList(String date, String LogBody, String LogSubject){
super();
this.logDate = date;
this.logBody = logBody;
this.logSubject = logSubject;
}
Seems wrong. As you have capitalized argument names, but you're setting the members with lowercase names.
Do you mean:
public LogList(String date, String logBody, String logSubject){
super();
this.logDate = date;
this.logBody = logBody;
this.logSubject = logSubject;
}
EDIT: Trivial thing, not impacting your code: You don't need your call to super() in your constructor as you're not extending any class.

Java Serialization

I'm learning now how to do serialization using Java Language. I have read some posts and docs about the subject and I tried to do a simple example (below)
public class SterializeObject implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private transient int code;
public SterializeObject (String n, int c){
name = n;
code = c;
}
public void printAtributes (){
System.out.println("name: " + name + "; code: " + code);
}
}
public class MainClass {
public static void main(String[] agrs) {
SterializeObject ob1 = new SterializeObject("ana", 1);
SterializeObject ob2 = new SterializeObject("rita", 2);
try {
FileOutputStream fileOut = new FileOutputStream("file.data");
ObjectOutputStream outObj = new ObjectOutputStream(fileOut);
outObj.writeObject(ob1);
outObj.writeObject(ob2);
outObj.close();
System.out.println("Objects were serialized!");
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<SterializeObject> list = new ArrayList<SterializeObject>();
try {
FileInputStream fileInput = new FileInputStream("file.data");
ObjectInputStream inputObj = new ObjectInputStream(fileInput);
Object o;
try {
while ((o = inputObj.readObject()) != null) {
list.add((SterializeObject) o);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Erro foi aqui! (1)");
}
inputObj.close();
fileInput.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erro foi aqui! (2)");
}
for (int i = 0; i < list.size(); ++i) {
list.get(i).printAtributes();
}
}
}
I created a Class SterializeObject that implements java.io.Serializable with two variables: one string (name) and one int (code) that is transient. Then In the main I generate two instances of that class and I tried to write it in a file, that I have done successfully! After that, I try to read the two object with a Loop.. there is my problem.. since the ObjectInputStream dosen't have some kind of method to see if we are in the end or not. So, I tried to do with this condition: (o = inputObj.readObject()) != null.
My output is this:
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at MainClass.main(MainClass.java:30)
Objects were serialized!
Erro foi aqui! (2)
name: ana; code: 0
name: rita; code: 0
I get the objects, but I get an error because, I think, is trying to access to something that doesn't exist.
Someone can tell me other way to do it?
Best Regards.
Read as many objects as the number of written objects, or write the list of objects itself, instead of writing every object one after the other.
(Or rely on the EOFException to detect the end of the stream, but this is ugly).
As many of you told me to do, I created a ArrayList and serialized the ArrayList.
My code is:
public class MainClass {
public static void main(String[] agrs) {
SterializeObject ob1 = new SterializeObject("ana", 1);
SterializeObject ob2 = new SterializeObject("rita", 2);
ArrayList <SterializeObject> list = new ArrayList<>();
list.add(ob1);
list.add(ob2);
ArrayList <SterializeObject> input = new ArrayList<SterializeObject>();
try {
FileOutputStream fileOut = new FileOutputStream("file.data");
ObjectOutputStream outObj = new ObjectOutputStream(fileOut);
outObj.writeObject(list);
outObj.close();
System.out.println("Objects were serialized!");
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fileInput = new FileInputStream("file.data");
ObjectInputStream inputObj = new ObjectInputStream(fileInput);
Object o;
try {
input = (ArrayList<SterializeObject>) inputObj.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Erro foi aqui! (1)");
}
inputObj.close();
fileInput.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erro foi aqui! (2)");
}
for (int i = 0; i < input.size(); ++i) {
input.get(i).printAtributes();
}
}
}
And the output is:
Objects were serialized!
name: ana; code: 0
name: rita; code: 0
Thank you for the help!
Close the FileOutputStream also along with ObjectOutputStream
fileOut.close();
Why don't you add both object to an ArrayList, and serialize the ArrayList. Then you just have to Deserialize the ArrayList and it will be populated with both objects.
You can do this by placing the readObject call inside a try-catch block and catching that EOFException you get, signaling you have read all the objects.
Replace your while loop with this piece of code
do{
try
{
o = inputObj.readObject();
list.add((SterializeObject) o);
}
catch(EOFException e)
{
o = null;
}
}while (o != null);

ObjectOutputStream, ObjectInputStream, and headers [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to understand object serialization better, so I am practicing with some code I got from my textbook. (My textbook doesn't explain how to read and write/append objects to a serialization file every time the program starts, which is what I need to do.) I took their program, which just overwrites existing data in a file with the objects from the current session, and add code to it so that it will append the objects and read the whole file instead. I found something really useful here: Appending to an ObjectOutputStream but even if I create a subclass of ObjectOutputStream, override the writeStreamHeader method, and call this subclass if the file already exists, which is what they did, it still throws a CorruptedStreamException. My guess is that I would need to set the pointer back to the beginning of the file, but that doesn't seem to be necessary as there is only one ObjectOutputStream. So, my question is, what else could I possibly need to do?
EDIT: Here is some code.
WriteData.java
import java.io.*;
import java.util.Scanner;
public class WriteData
{
private int number;
private String name;
private float money;
private ObjectInputStream testopen;
private ObjectOutputStream output; //This is for the output. Make sure that
//this object gets an instance of FileOutputStream so that it can write objects
//to a FILE.
private AppendObjectOutputStream appendobjects;
static Scanner input = new Scanner(System.in);
static DataClass d;
public void openfile()
{
//Try opening a file (it must have the ".ser" extension).
try
{
//output = new ObjectOutputStream(new FileOutputStream("test.ser"));
testopen = new ObjectInputStream(new FileInputStream("test.ser"));
}
//If there is a failure, throw the necessary error.
catch (IOException exception)
{
try
{
output = new ObjectOutputStream(new FileOutputStream("test.ser"));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} //end case createfile
if (testopen != null)
{
try
{
testopen.close();
appendobjects = new AppendObjectOutputStream(
new FileOutputStream("test.ser"));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void writedata()
{
//write the data until the user enters a sentry value.
System.out.println("Enter CTRL + z to stop input.\n");
System.out.print ("Enter the data in the following format: " +
"account_number name balance\n->");
while (input.hasNext())
{
System.out.print ("Enter the data in the following format: " +
"account_number name balance\n->");
try
{
number = input.nextInt();
name = input.next();
money = input.nextFloat();
//Make object with that data
d = new DataClass(number, name, money);
//write it to the file
if (output != null)
{
output.writeObject(d);
}
else if (appendobjects != null)
{
appendobjects.writeObject(d);
}
}
catch (IOException e)
{
System.out.println("Error writing to file.");
return;
}
}
System.out.println("\n");
} //end writedata
public void closefile()
{
try
{
if (output != null)
{
output.close();
}
else if (appendobjects != null)
{
appendobjects.close();
}
}
catch (IOException e)
{
System.out.println("Error closing file. Take precautions");
System.exit(1);
}
}
}
DataClass.java
import java.io.Serializable;
public class DataClass implements Serializable
{
private int someint;
private String somestring;
private float somefloat;
public DataClass(int number, String name, float amount)
{
setint(number);
setstring(name);
setfloat(amount);
}
public void setint(int i)
{
this.someint = i;
}
public int getint()
{
return someint;
}
public void setstring(String s)
{
this.somestring = s;
}
public String getstring()
{
return somestring;
}
public void setfloat(float d)
{
this.somefloat = d;
}
public float getfloat()
{
return somefloat;
}
}
AppendObjectOutputStream.java
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
public class AppendObjectOutputStream extends ObjectOutputStream
{
public AppendObjectOutputStream(FileOutputStream arg0) throws IOException
{
super(arg0);
// TODO Auto-generated constructor stub
}
//This is a function that is default in ObjectOutputStream. It just writes the
//header to the file, by default. Here, we are just going to reset the
//ObjectOutputStream
#Override
public void writeStreamHeader() throws IOException
{
reset();
}
}
ReadData.java
import java.io.*;
import java.util.Scanner;
public class ReadData
{
private FileInputStream f;
private ObjectInputStream input; //We should the constructor for this
//object an object of FileInputStream
private Scanner lines;
public void openfile()
{
try
{
f = new FileInputStream("test.ser");
input = new ObjectInputStream (f);
//input.reset();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
public void readdata()
{
DataClass d;
System.out.printf("%-15s%-12s%10s\n", "Account Number", "First Name",
"Balance");
try
{
while (true)
{
d = (DataClass)input.readObject(); //define d
//read data in from d
System.out.printf("%-15d%-12s%10.2f\n", d.getint(), d.getstring(),
d.getfloat());
}
}
catch (EOFException eof)
{
return;
}
catch (ClassNotFoundException e)
{
System.err.println("Unable to create object");
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void closefile()
{
try
{
if (input != null)
{
input.close();
}
}
catch (IOException ex)
{
System.err.println("Error closing file.");
System.exit(1);
}
}
}
SerializationTest.java
public class SerializationTest
{
public static void main(String[] args)
{
ReadData r = new ReadData();
WriteData w = new WriteData();
w.openfile();
w.writedata();
w.closefile();
r.openfile();
r.readdata();
r.closefile();
}
}
I suggest to do it this way
ObjectOutputStream o1 = new ObjectOutputStream(new FileOutputStream("1"));
... write objects
o1.close();
ObjectOutputStream o2 = new AppendingObjectOutputStream(new FileOutputStream("1", true));
... append objects
o2.close();
it definitely works.
import EJP;
import Evgeniy_Dorofeev;
public class answer
{
private String answera, answerb;
public answer(String a, String b)
{
answera = a;
answerb = b;
}
public void main(String[] args)
{
answer(EJP.response(), Evgeniy_Dorofeev.response());
System.out.println(answera + '\n' + answerb);
}
}
You need to add a 'true' for the append parameter of new FileOutputStream() in the case where you are appending. Otherwise you aren't. Appending, that is.

Categories

Resources