Serialized Object file is empty when program has no errors - java

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.

Related

resource leak and output file is not writing

I get a resource leak warning in return new ArrayList<>();. The file is not writing in the friends.txt which I am trying to save list in a text file. Please help.
import java.io.*;
import java.util.ArrayList;
public class ReadWrite {
public void writeFriends(ArrayList<Friend> friends) {
FileOutputStream friendFile;
ObjectOutputStream friendWriter;
try {
friendFile = new FileOutputStream(new File("C:\\Users\\aa\\Desktop\\src\\friends.txt"));
friendWriter = new ObjectOutputStream(friendFile);
if(friends.size() >0) {
friendWriter.writeInt(friends.size());
for (Friend friend : friends) {
friendWriter.writeObject(friend);
}
}
else {
System.out.println("No data to write");
}
friendWriter.close();
friendFile.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found. Retry after creating File 'Friends.txt'");
} catch (IOException e) {
System.out.println("Stream cannot be initialized.");
}
}
public ArrayList<Friend> readFriends() {
FileInputStream friendFile;
ObjectInputStream friendReader;
ArrayList<Friend> friends = new ArrayList<>();
try {
friendFile = new FileInputStream(new File("C:\\Users\\aa\\Desktop\\src\\friends.txt"));
friendReader = new ObjectInputStream(friendFile);
int size = friendReader.readInt();
if(size > 0){
for (int i = 0; i < friendReader.readInt(); i++) {
friends.add((Friend) friendReader.readObject());
}
}
else{
System.out.println("Empty File");
return new ArrayList<>();
}
friendReader.close();
friendFile.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found. Retry after creating File 'Friends.txt'");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("Stream cannot be inititalized");
}
return friends;
}
}
I am trying to save a list of friends in the friends.txt file. I see no output in the friends.txt file. Is it something to do with my location or FileOutputStream ?
You have two problems in your code.
There is a bug in the for loop in method readFriends of class ReadWrite.
The file friends.txt may not be closed.
Here is the corrected code. Note that I could not find the code for class Friend in your question so I wrote a minimal class. Since you are using serialization, I assume that class Friend implements interface Serializable.
Notes after the code.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
public class ReadWrite {
public void writeFriends(ArrayList<Friend> friends) {
try (OutputStream friendFile = Files.newOutputStream(Paths.get("C:", "Users", "aa", "Desktop", "src", "friends.dat"));
ObjectOutputStream friendWriter = new ObjectOutputStream(friendFile)) {
if (friends.size() > 0) {
friendWriter.writeInt(friends.size());
for (Friend friend : friends) {
friendWriter.writeObject(friend);
}
}
else {
System.out.println("No data to write");
}
}
catch (FileNotFoundException e) {
System.out.println("File Not Found. Retry after creating File 'friends.dat'");
e.printStackTrace();
}
catch (IOException e) {
System.out.println("Stream cannot be initialized.");
e.printStackTrace();
}
}
public ArrayList<Friend> readFriends() {
ArrayList<Friend> friends = new ArrayList<>();
try (InputStream friendFile = Files.newInputStream(Paths.get("C:", "Users", "aa", "Desktop", "src", "friends.dat"));
ObjectInputStream friendReader = new ObjectInputStream(friendFile)) {
int size = friendReader.readInt();
if (size > 0) {
for (int i = 0; i < size; i++) {
friends.add((Friend) friendReader.readObject());
}
}
else {
System.out.println("Empty File");
return new ArrayList<>();
}
}
catch (FileNotFoundException e) {
System.out.println("File Not Found. Retry after creating File 'friends.dat'");
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
System.out.println("Stream cannot be inititalized");
e.printStackTrace();
}
return friends;
}
public static void main(String[] args) {
ArrayList<Friend> friends = new ArrayList<>();
Friend friend = new Friend("Jane");
friends.add(friend);
ReadWrite rw = new ReadWrite();
rw.writeFriends(friends);
ArrayList<Friend> newFriends = rw.readFriends();
System.out.println(newFriends);
}
}
class Friend implements Serializable {
private String name;
public Friend(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
In the for loop condition in method readFriends you have the following:
friendReader.readInt()
This means that in every loop iteration, you are trying to read another int from the file friends.txt. This call fails since there is only one int in the file. Hence you need to use size which is the variable that contains the only int in file friends.txt which you read before the for loop.
Since you are using serialization, it is recommended to give the file name an extension of .dat rather than .txt since the file is not a text file.
I always write printStackTrace() in my catch blocks since that helps me to locate the cause of the exception. You actually should not get a FileNotFoundException since Java will create the file if it doesn't exist. If Java fails to create the file, then it is probably because the user has no permission to create a file, so displaying an error message saying to create the file before running your code probably won't help.
Your code may successfully open the file and write some data to it and crash before you have written all the data. In that case, your code does not close the file. If you are using at least Java 7, then you should use try-with-resources to ensure that the files are always closed.
Java 7 also introduced NIO.2 as a better API for interacting with the computer's file system from Java code. I suggest that you use it as I have shown in the code, above.

Reading objects from a file and adding them to an array

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();

Populate a Java File object at compile time

I have a third-party library that requires the populating of a java File object at runtime. I have extended this code, but I do not need the file-related part. However, for my purposes, I am forced to create and use the File object and read from it.
Is there a way I can have the binary equivalent of an already-read file available at runtime? Or is there a way to have a file as byte-code already available for a File object? Please assume with my situation that going to a file-system to retrieve and open a file is not an option.
Thanks for any insights!
You can create a temp file and delete after your program finishes.
import java.io.*;
import java.nio.file.*;
public class Program {
public static final File EMPTY_FILE = createTmpFile("empty.dat");
private static final File createTmpFile(final String filename) {
String tmpDir = System.getProperty("java.io.tmpdir");
Path filePath = Paths.get(tmpDir, filename);
return filePath.toFile();
}
public static void main(String[] args) {
try {
// Do stuff...
System.out.println(EMPTY_FILE.getCanonicalPath());
Thread.sleep(2000);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
// Cleanup...
EMPTY_FILE.delete();
}
}
}
If you need a PHYSICAL file on they system, you can create it like so:
import java.io.*;
import java.nio.file.*;
public class Program {
public static final String TMP_DIR = System.getProperty("java.io.tmpdir");
public static final File EMPTY_FILE = createTmpFile("empty.dat");
private static final File createTmpFile(final String filename) {
Path filePath = null;
try {
byte[] data = { 0 }; // Write a single byte of data
filePath = Files.write(Paths.get(TMP_DIR, filename), data);
} catch (IOException e) {
e.printStackTrace();
}
return filePath.toFile();
}
public static void main(String[] args) {
try {
// Do stuff...
System.out.println(EMPTY_FILE.getCanonicalPath());
Thread.sleep(2000);
} catch (InterruptedException | IOException e) {
e.printStackTrace();
} finally {
// Cleanup...
EMPTY_FILE.delete();
}
}
}

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.

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