File Structured Error [duplicate] - java

This question already has an answer here:
StreamCorruptedException: invalid type code: AC
(1 answer)
Closed 5 years ago.
sorry to bother you, once again I need help on the Java language , more precisely on the file structured as the title .
The error in question is that after you have stored more than once , I read reports an error (of course putting in append mode) , and does so even if I do all in the main program ...
My program consists of three classes in three files:
Alluno.java:
import java.io.Serializable;
class Alunno implements Serializable {
private String nome, cognome, data_nascita, indirizzo, residenza, telefono;
public Alunno() {
nome = ""; cognome = ""; data_nascita = ""; indirizzo = ""; residenza = ""; telefono = "";
}
public void setNome(String nome) {
this.nome = nome;
}
void setCognome(String cognome) {
this.cognome = cognome;
}
void setData_Nascita(String data_nascita) {
this.data_nascita = data_nascita;
}
void setIndirizzo(String indirizzo) {
this.indirizzo = indirizzo;
}
void setResidenza(String residenza) {
this.residenza = residenza;
}
void setTelefono(String telefono) {
this.telefono = telefono;
}
}
File.java:
import java.io.*;
class File {
private int dim;
public Alunno nuovoAlunno() throws IOException {
BufferedReader t = new BufferedReader(new InputStreamReader(System.in));
Alunno a = new Alunno();
System.out.println("***Inserimento nuovo alunno***");
System.out.format("Nome: ");
a.setNome(t.readLine());
System.out.format("Cognome: ");
a.setCognome(t.readLine());
System.out.format("Data di nascita: ");
a.setData_Nascita(t.readLine());
System.out.format("Indirizzo: ");
a.setIndirizzo(t.readLine());
System.out.format("Residenza: ");
a.setResidenza(t.readLine());
System.out.format("Telefono: ");
a.setTelefono(t.readLine());
return a;
}
public void sciviFile(Alunno a) {
try {
FileOutputStream f = new FileOutputStream("istituto.dat", true);
ObjectOutputStream fOUT = new ObjectOutputStream(f);
fOUT.writeObject(a);
fOUT.flush();
fOUT.close();
} catch (Exception e) {
System.out.println("Eccezione scrittura: " + e.getMessage());
}
}
public void leggiFile() {
Alunno a;
try {
FileInputStream f = new FileInputStream("istituto.dat");
ObjectInputStream fIN = new ObjectInputStream(f);
while (true) {
try {
a = (Alunno) fIN.readObject();
dim++;
System.out.println("Dimensione file: " + dim);
} catch (EOFException e) {
break;
}
}
f.close();
} catch (Exception e) {
System.out.println("Eccezione lettura: " + e.getMessage());
}
}
}
IstitutoScolastico.java:
import java.io.*;
public class IstitutoScolastico {
public static void main(String[] args) throws IOException {
File f = new File();
//f.sciviFile(f.nuovoAlunno());
f.leggiFile();
}
}
OUTPUT:
Dimensione file: 1
Eccezione lettura: invalid type code: AC
I do not read more than one object if I put in append mode, where did I go wrong?
Ah, anyway sorry for the grammatical errors, but I'm Italian and I helped with google translate!

The problem is that ObjectOutputStream writes a header to the file in it's constructor.
Since you call the constructor for each Alunno you append, you write a new header to the file too.
However ObjectInputStream expects only one header(at the start of the file).
If you don't want to change much in your code, you should create a new ObjectInputStream for each Alunno you read, change the code in your File class:
public void leggiFile() {
Alunno a;
try {
FileInputStream f = new FileInputStream("istituto.dat");
try {
while (true) {
// the header is read in the constructor
ObjectInputStream fIN = new ObjectInputStream(f);
a = (Alunno) fIN.readObject();
dim++;
System.out.println("Dimensione file: " + dim);
}
} catch (EOFException e) { }
f.close();
} catch (Exception e) {
System.out.println("Eccezione lettura: " + e.getMessage());
}
}
A alternative would be to skip 2(?) shorts (4(?) bytes) from the FileInputStream, but if the definition of the header should change (although this seems unlikely), you might have to change your code.
Another alternative would be to read all the Alunnos that are already in the file and then write all Alunnos (including the new one) to the File starting at the beginning of the file. But this may not be as fast as you wish.
For detailed information you can read http://docs.oracle.com/javase/7/docs/platform/serialization/spec/output.html and http://docs.oracle.com/javase/7/docs/platform/serialization/spec/input.html
One last tip: If you use Java SE 7 (or higher) consider using try-with-resources for your streams.

Related

How to make ObjectInputStream read all objects from file in java?

I have a file which is storing objects and I have a *getAll() method which needs to return the List<Secretary>. But, I only see single object being printed in console.
I searched for the problem and tried 3 ways but it did not work.
The insert method for inserting object in file is:
#Override
public Secretary insert(Secretary t) {
try {
System.out.println("insert called");
FileOutputStream file = new FileOutputStream
(filename,true);
ObjectOutputStream out = new ObjectOutputStream
(file);
Method for serialization of object
out.writeObject(t);
out.close();
file.close();
return t;
}
catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
I have declared append mode as true as, my file was being replaced by new object when saving.
So,i need to fetch all object from file and need to assign to a list.I tried:
public class SecretaryDaoImpl implements SecretaryDAO{
private String filename = "secretary.txt";
private Secretary sec=null;
#Override
public List<Secretary> getAll() {
//Method 1
try {
Reading the object from a file
FileInputStream file = new FileInputStream
(filename);
ObjectInputStream in = new ObjectInputStream
(file);
List<Secretary> secList=new ArrayList<>();
Method for deserialization of object
secList.add((Secretary)in.readObject());
in.close();
file.close();
System.out.println("Object has been deserialized\n"
+ "Data after Deserialization.");
System.out.println("secList is" +secList);
return secList;
}
catch (IOException ex) {
System.out.println("Secreatary file not found");
return null;
}
catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException" +
" is caught");
}
return null;
//Method 2
List<Secretary> secList=new ArrayList<>();
ObjectInputStream objectinputstream = null;
try {
FileInputStream streamIn = new FileInputStream(filename);
objectinputstream = new ObjectInputStream(streamIn);
List<Secretary> readCase = (List<Secretary>) objectinputstream.readObject();
for(Secretary s:readCase){
secList.add(s);
}
System.out.println("seclist is" + secList);
return secList;
} catch (Exception e) {
e.printStackTrace();
} finally {
if(objectinputstream != null){
try {
objectinputstream.close();
} catch (IOException ex) {
Logger.getLogger(SecretaryDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//Method 3
try{
File file = new File(filename);
List<Secretary> list = new ArrayList<>();
if (file.exists()) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
list.add((Secretary) ois.readObject());
}
}
System.out.println("getall is"+list);
}
catch(Exception e){
}
return null;
}
}
I have commented out my code but here while posting in stackoverflow I have uncommented all the codes.
My Secretary.java is :
package com.npsc.entity;
import java.io.Serializable;
/**
*
* #author Ashwin
*/
public class Secretary implements Serializable {
private static final long serialVersionUID = 6529685098267757690L;
private int id;
private String userName;
private String password;
private Branch branch;
public String getUserName() {
return userName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Secretary(String userName, String password) {
this.userName = userName;
this.password = password;
}
public Branch getBranch() {
return branch;
}
public void setBranch(Branch branch) {
this.branch = branch;
}
#Override
public String toString() {
return "Secretary{" + "id=" + id + ", userName=" + userName + ", password=" + password + ", branch=" + branch + '}';
}
}
While performing insert operation,my txt file saving objects is:
But,I am unable to read all the object and add in list.Where I am facing the problem?
You will need to store in the file, the number of Secretary objects to read back. You can then determine how many entities to read, and thus repopulate your list.
Something like:
List<Secretary> list;
private void persistList(ObjectOutputStream out) {
out.writeInt(list.size());
for (Secretary sec : list) {
out.writeObject(sec);
}
}
And then to read:
private List<Secretary> readFromStream(ObjectInputStream in) {
int numObjects = in.readInt();
List<Secretary> result = new ArrayList<>(numObjects);
for (int i = 0; i < numObjects; i++) {
result.add((Secretary)in.readObject());
}
return result;
}
This is just a sketch of the technique (and ignores error handling, stream opening/closing etc.); the main thing is to integrate the idea of recording the size of the list, then reading that many Secretaries into your existing code.
Write a List<Secretary> to file and read same back, then you will have all.
write (Secretary s) {
read List<Secretary> currentList ;
currentList.add(s)
write List<Secretary>
}

Print To File in Java

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

Java: My ArrayList empties itself as soon as I empty the text file from which the ArrayList gets its contents

I´m writing my own library in java, where you can save variables very simple. But I have a problem in changing the values of the variables. The ArrayList empties itself as soon as the txt file is empty.
My Code:
public class SaveGameWriter {
private File file;
private boolean closed = false;
public void write(SaveGameFile savegamefile, String variableName, String variableValue, SaveGameReader reader) throws FileNotFoundException
{
if(!reader.read(savegamefile).contains(variableName))
{
file = savegamefile.getFile();
OutputStream stream = new FileOutputStream(file, true);
try {
String text = variableName+"="+variableValue;
stream.write(text.getBytes());
String lineSeparator = System.getProperty("line.separator");
stream.write(lineSeparator.getBytes());
}catch(IOException e)
{}
do {
try {
stream.close();
closed = true;
} catch (Exception e) {
closed = false;
}
} while (!closed);
}
}
public void setValueOf(SaveGameFile savegamefile, String variableName, String Value, SaveGameReader reader) throws IOException
{
ArrayList<String> list = reader.read(savegamefile);
if(list.contains(variableName))
{
list.set(list.indexOf(variableName), Value);
savegamefile.clear();
for(int i = 0; i<list.size()-1;i+=2)
{
write(savegamefile,list.get(i),list.get(i+1),reader);
}
}
}
}
Here my SaveGameReader class:
public class SaveGameReader {
private File file;
private ArrayList<String> result = new ArrayList<>();
public String getValueOf(SaveGameFile savegamefile, String variableName)
{
ArrayList<String> list = read(savegamefile);
if(list.contains(variableName))
{
return list.get(list.indexOf(variableName)+1);
}else
return null;
}
public ArrayList<String> read(SaveGameFile savegamefile) {
result.clear();
file = savegamefile.getFile();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("=");
for (String part : splited) {
result.add(part);
}
}
} catch (IOException e) {
} finally {
boolean closed = false;
while(!closed)
{
try {
in.close();
closed=true;
} catch (Exception e) {
closed=false;
}
}
}
result.remove("");
return result;
}
}
And my SaveGameFile class:
public class SaveGameFile {
private File file;
public void create(String destination, String filename) throws IOException {
file = new File(destination+"/"+filename+".savegame");
if(!file.exists())
{
file.createNewFile();
}
}
public File getFile() {
return file;
}
public void clear() throws IOException
{
PrintWriter pw = new PrintWriter(file.getPath());
pw.close();
}
}
So, when I call the setValueOf() methode the ArrayList is empty and in the txt file there´s just the first variable + value. Hier´s my data structure:
Name=Testperson
Age=40
Phone=1234
Money=1000
What´s the problem with my code?
In your SaveGameReader.read() method you have result.clear(); which clears ArrayList. And you do it even before opening the file. So basically before every read from file operation you are cleaning up existing state and reread from file. If file is empty then you finish with empty list

Java: Write HashMap into File

I'm working on a program that saves two words into a HashMap. I need to be able to take the HashMap key and value and write it into a file as "key:value" format. When my save() method is called, the HashMap contents are supposed to be written into the file whose name was given as parameter to the constructor. The method returns false if the file can't be saved; otherwise it returns true. However, its not working if the File does not exist. It's also not saving changes made to an existing file. I'm not understanding how to read/write files too well... Thank you.
package dictionary;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Scanner;
public class MindfulDictionary {
private HashMap<String, String> words;
private File file;
public MindfulDictionary() {
this.words = new HashMap<String, String>();
}
public MindfulDictionary(String file) {
this.file = new File(file);
this.words = new HashMap<String, String>();
}
public boolean load() {
try {
Scanner fileReader = new Scanner(this.file);
while (fileReader.hasNextLine()) {
String line = fileReader.nextLine();
String[] parts = line.split(":"); // the line is split at :
String word = parts[0];
String trans = parts[1];
this.add(word, trans);
}
} catch (Exception e) {
System.out.println("nope");
}
return true;
}
public boolean save() {
boolean saved = true;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(this.file.getName(), true));
for (String key : this.words.keySet()) {
writer.write(key + ":" + this.words.get(key) + "\n");
writer.newLine();
writer.flush();
writer.close();
}
} catch (Exception e) {
}
return saved;
}
public void add(String word, String translation) {
if ((!this.words.containsKey(word))) {
this.words.put(word, translation);
}
}
public String translate(String word) {
if (this.words.containsKey(word)) {
return this.words.get(word);
} else if (this.words.containsValue(word)) {
for (String key : this.words.keySet()) {
if (this.words.get(key).equals(word)) {
return key;
}
}
}
return null;
}
public void remove(String word) {
if (this.words.containsKey(word)) {
this.words.remove(word);
} else if (this.words.containsValue(word)) {
String remove = "";
for (String key : this.words.keySet()) {
if (this.words.get(key).equals(word)) {
remove += key;
}
}
this.words.remove(remove);
}
}
}
Notice this part of your code,
try {
writer = new BufferedWriter(new FileWriter(this.file.getName(), true));
for (String key : this.words.keySet()) {
writer.write(key + ":" + this.words.get(key) + "\n");
writer.newLine();
writer.flush();
writer.close(); // !!
}
} catch (Exception e) {
}
Here, you are calling close() on the BufferedWriter object. You can not use the object after you have called close() on it.
Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown.
Read more about close() here.
Also, since you are catching all the exceptions and not doing anything with them, you did not notice the IOException . In future NEVER do this. At the least log any exception that occurs. This will help you with your debugging.

How to handle StreamCorruptedException when using ObjectInputStream? [duplicate]

This question already has an answer here:
StreamCorruptedException: invalid type code: AC
(1 answer)
Closed 5 years ago.
`I am new to java and getting StreamCorruptedException in the code below... In this code I am trying to read multiple objects from a file using ObjectInputStream... m not able to handle the StreamCorruptedException...the o/p I m getting is
File C098.txt already exists
Product ID:- P001
Description:- Book
Price:- Rs.200
Exception in thread "main" java.io.StreamCorruptedException: invalid type code:
AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1374)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at Utility.getProducts(Utility.java:57)
at Utility.main(Utility.java:23)
CODE:
import java.io.*;
import java.util.*;
class Product implements Serializable{
private static final long serialVersionUID = 1L;
String productId;
String desc;
String price;
public Product(String PId,String a_des,String a_price){
productId=PId;
desc=a_des;
price=a_price;
}
public String toString(){
return "Product ID:- "+productId+"\nDescription:- "+desc+"\nPrice:- "+price;
}
}
class Utility{
// Product objProduct;
public static void main(String args[]) throws Exception{
String cartId = "C098.txt";
Product objProduct = new Product("P001","Book","Rs.200");
addProductToCart(cartId,objProduct);
getProducts(cartId);
objProduct = new Product("P087","Laptop","Rs.45,500");
addProductToCart("C098.txt",objProduct);
getProducts(cartId);
}
public static void addProductToCart(String CId,Product p) throws Exception{
try{
boolean searchFile;
File objFile = new File(CId);
searchFile = objFile.exists();
if(searchFile)
System.out.println("File "+CId+" already exists");
else{
objFile.createNewFile();
System.out.println("File "+CId+" did not exist. It is now created");
}
FileOutputStream objFOS = new FileOutputStream(objFile,true);
ObjectOutputStream objO = new ObjectOutputStream(objFOS);
objO.writeObject(p);
objO.flush();
objO.close();
}catch(Exception e)
{
System.out.println("Exception Caught");
}
}
public static void getProducts(String CId) throws Exception{
Product objProduct1 = new Product("","","");
File objFile1 = new File(CId);
FileInputStream objFIS = new FileInputStream(objFile1);
ObjectInputStream objI = new ObjectInputStream(objFIS);
Object obj = null;
try{
while((obj=objI.readObject()) != null){
if (obj instanceof Product) {
System.out.println(((Product)obj).toString());
}
}
}catch (EOFException ex) { //This exception will be caught when EOF is reached
System.out.println("End of file reached.");
}finally {
//Close the ObjectInputStream
try{
if (objI != null)
objI.close();
}catch (IOException ex) {
ex.printStackTrace();
}
}
}
}`
The problem is because of header issue, You are appending to same file and while returning second object it throws exception because of headers issue. try to write object in different files, you can rid out of the problem.
SCE Thrown when control information that was read from an object stream violates internal consistency checks.
try
import java.io.*;
import java.util.*;
class Product implements Serializable{
private static final long serialVersionUID = 1L;
String productId;
String desc;
String price;
public Product(String PId,String a_des,String a_price){
productId=PId;
desc=a_des;
price=a_price;
}
public String toString(){
return "Product ID:- "+productId+"\nDescription:- "+desc+"\nPrice:- "+price;
}
// Product objProduct;
public static void main(String args[]) throws Exception{
String cartId = "C0982.txt";
Product objProduct = new Product("P001","Book","Rs.200");
addProductToCart(cartId,objProduct);
getProducts(cartId);
Product objProduct1 = new Product("P087","Laptop","Rs.45,500");
addProductToCart("C0981.txt",objProduct1);
getProducts("C0981.txt");
}
public static void addProductToCart(String CId,Product p) throws Exception{
try{
boolean searchFile;
File objFile = new File(CId);
searchFile = objFile.exists();
if(searchFile)
System.out.println("File "+CId+" already exists");
else{
objFile.createNewFile();
System.out.println("File "+CId+" did not exist. It is now created");
}
FileOutputStream objFOS = new FileOutputStream(objFile,true);
ObjectOutputStream objO = new ObjectOutputStream(objFOS);
objO.writeObject(p);
objO.flush();
objO.close();
}catch(Exception e)
{
System.out.println("Exception Caught");
}
}
public static void getProducts(String CId) throws Exception{
Product objProduct1 = new Product("","","");
File objFile1 = new File(CId);
FileInputStream objFIS = new FileInputStream(objFile1);
ObjectInputStream objI = new ObjectInputStream(objFIS);
Object obj = null;
try{
while((obj=objI.readObject()) != null){
if (obj instanceof Product) {
System.out.println(((Product)obj).toString());
}
}
}catch (EOFException ex) { //This exception will be caught when EOF is reached
System.out.println("End of file reached.");
}finally {
//Close the ObjectInputStream
try{
if (objI != null)
objI.close();
}catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
</pre>
You can't 'handle' it. You have to prevent it. It results from a design error such as using two ObjectOutputStreams on a stream that is read by a single ObjectInputStream, as you are doing here by appending to the file, or writing data other than objects and not reading it symmetrically.

Categories

Resources