Deserializing an Object only reads one data - java

how do read file data from file/Deserializing an object.I have created a file which is binary file which contains list of companies data i am able to add new company and its related data but when i want to read back all the file datas it only gives first company datas and it prints null ..what is the problem below is what i have done
public class CompanyInfo extends Company {
int counter=0;
Scanner in=new Scanner(System.in);
private ArrayList<Company> companyinfo;
public CompanyInfo() {
companyinfo=new ArrayList<Company>();
}
public void registercompany() {
System.out.println("Enter Company Name \n");
companyName=in.nextLine();
System.out.println("\n");
System.out.println("Enter Company Code \n");
companyCode=in.nextLine();
System.out.println("\n");
System.out.println("Enter the Share Number \n");
shareNo=in.nextInt();
System.out.println("\n");
System.out.println("Enter Closing Rate \n");
closingRate=in.nextDouble();
Company cin=new Company(companyName,companyCode,shareNo,closingRate);
companyinfo.add(cin);
try {
ObjectOutputStream outObjFile =new ObjectOutputStream(new FileOutputStream("companies.dat",true));
Company company = new Company(companyName,companyCode,shareNo,closingRate);
outObjFile.writeObject(company);
outObjFile.writeChars("\n");
outObjFile.close();
} catch (Exception e) {
// TODO: handle exception
System.out.println("A file error has occurred. Sorry.");
System.out.println( e.getMessage() );
}
counter++;
}
public void viewcompany(){
try {
ObjectInputStream inObjFile = new ObjectInputStream(
new FileInputStream("companies.dat"));
System.out.println(inObjFile.readObject()); // displays first object
Company company = (Company)inObjFile.readObject(); // restores object
System.out.println(company); // displays restored object
inObjFile.close(); // finished with the file now.
} catch (Exception e) {
System.out.println(e.getMessage());
}

I will do two different ways.
Add all details into hashmap and serialize that object. So while reading back, I can search using "key". Key can be name or ID of company. You can do same with ArrayList as well. Search may be difficult. Immutable collections from Guava are less memory used and more better.
Another solution is create object file with key.dat and put into a directory called company. So easy to read back and do search as well.

finally i found the answer ...Hope it helps to others too..good luck
public class CompanyInfo extends Company {
int counter=0;
private static String filename = "company.dat";
Scanner in=new Scanner(System.in);
private ArrayList<Company> companyinfo;
public CompanyInfo() {
companyinfo=new ArrayList<Company>();
}
public void registercompany() {
System.out.println("Enter Company Name \n");
companyName=in.nextLine();
System.out.println("Enter Company Code \n");
companyCode=in.nextLine();
System.out.println("Enter the Share Number \n");
shareNo=in.nextInt();
System.out.println("Enter Closing Rate");
closingRate=in.nextDouble();
Company cin=new Company(companyName,companyCode,shareNo,closingRate);
companyinfo.add(cin);
File file=new File(filename);
boolean append=true;
ObjectOutputStream out=null;
try {
if (!file.exists()||!append) {
out=new ObjectOutputStream(new FileOutputStream(filename));
}
else
{
out=new AppendableObjectOutputStream(new FileOutputStream (filename, append));
}
Company company = new Company(companyName,companyCode,shareNo,closingRate);
out.writeObject(company);
out.flush();
} catch (Exception e){
e.printStackTrace ();
}finally{
try{
if (out != null) out.close ();
}catch (Exception e){
e.printStackTrace ();
}
}
counter++;
}
public void viewcompany(){
try {
List<Object> results = new ArrayList<Object>();
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
try{
while (true) {
results.add(ois.readObject());}
}
catch (OptionalDataException e) {
if (!e.eof) throw e; }
finally {
System.out.println(results);
//System.out.println(((Company)results.get(0)).companyName);
ois.close(); }
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
private static class AppendableObjectOutputStream extends ObjectOutputStream {
public AppendableObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
#Override
protected void writeStreamHeader() throws IOException {}
}
}

Related

why I can't add my answer to readwrite.txt.?

I try to add my answer to readwrite.txt, but I don't find my answer every time I run the code.
public static void main(String[] args) {
ArrayList<String> category1=new ArrayList<>();
category1.add("die hard");
category1.add("7.5");
category1.add("mission impossible");
category1.add("8");
category1.add("the expendabels");
category1.add("6");
ArrayList<String> category2=new ArrayList<>();
category2.add("the mask");
category2.add("due date");
ArrayList<String>userchoices=new ArrayList<>();
Scanner s= new Scanner(System.in);
System.out.println("select a movie");
String answer=s.nextLine();
String writepath="files/readwrite.txt";
try {
FileWriter writer=new FileWriter(writepath);
writer.write(answer);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (category1.contains(answer)) {
System.out.println(category1.get(category1.indexOf(answer) + 1) +
(" of 10"));
System.out.println("action");
}
if (answer.equals("action"))
System.out.println(category1);
else if (category2.contains(answer))
System.out.println("comedy");
if (answer.equals("comedy"))
System.out.println(category2);
}
}
I try to add my answer to readwrite.txt, but I don't find my answer every time I run the code.
You need to close your FileWriter when you are done with writing to file. When you call close() writer will flush its internal buffer to disk and you will see that text appears in file. Also it is a must to close any resources when you do not need them.

Assistance with writing/reading to and from vector in JAVA

I have a project where I am required to read and write a vector of bank account objects and I am struggling with this concept. I was able to figure it out when the accounts were not stored in a vector but now that I am dealing with vectors I am confused. If anyone can look at my code I would greatly appreciate it! Thanks in advance for your time!
This is my best attempt. Even though I know it's wrong, I just wanted to give you an idea of what I am trying to do.
public static void readTrans()
{
textArea.setText("");
chooseFile(1);
try
{
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fis);
for (int index=0; index != fileIndex; index++)
{
account = (CheckingAccount)in.readObject();
acctStore.add(index, account);
System.out.println("reading account " + acctStore.elementAt(index));
}
saveStatus = true;
in.close();
}
catch(ClassNotFoundException e)
{
System.out.println(e);
}
catch (IOException e)
{
System.out.println(e);
}
}
public static void writeTrans()
{
textArea.setText("");
chooseFile(2);
try
{
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(fos);
for (int index=0; index != acctStore.size(); index++)
{
out.writeObject(acctStore.elementAt(index));
System.out.println("Writing account for " + acctStore.elementAt(index).getName() +" with initial balance: " + acctStore.elementAt(index).getBalance());
fileIndex++;
}
saveStatus = true;
out.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
UPDATE:
Ok I think I figured it out however I am getting a warning since I casted the vector onto the CheckingAccount. Is this practice okay? The program is working as I expected so I am assuming so. Thanks again for your time!
Here's updated code:
public static void readTrans()
{
textArea.setText("");
chooseFile(1);
try
{
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fis);
acctStore = (Vector<CheckingAccount>)in.readObject();
saveStatus = true;
in.close();
}
catch(ClassNotFoundException e)
{
System.out.println(e);
}
catch (IOException e)
{
System.out.println(e);
}
}
public static void writeTrans()
{
textArea.setText("");
chooseFile(2);
try
{
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(acctStore);
saveStatus = true;
out.close();
}
catch(IOException e)
{
System.out.println(e);
}
}

Serialized object java

Today I started using serialized object in java, I'm new at it and I have some problems when I try to deserialize.
I have this file where I write all my Account objects, it writes fine I guess. The problem is I don't know how to refer to a specific object from that file, or how could I get all of them into a list? and then refer to it.
This is how i'm trying to read them:
public void readAccount(Account e) {
/* List<Account> results = new ArrayList<Account>();
try {
FileInputStream fileIn = new FileInputStream("test.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
for (int i = 0; i < accBank.size(); i++) {
results.add((Account) 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;
}
for (Account acc : results) {
System.out.println(toString(acc));
if(e.getAcc_no() == acc.getAcc_no())
{System.out.println("Deserialized Account...");
System.out.println(toString(e));
}
}
*/
List<Account> results = new ArrayList<Account>();
Account acc = null;
FileInputStream fis = null;
try {
fis = new FileInputStream("test.txt");
while (true) {
ObjectInputStream ois = new ObjectInputStream(fis);
results.add((Account) ois.readObject());
acc = (Account) ois.readObject();
}
} catch (Exception ignored) {
// as expected
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
System.out.println("results = " + results);
for (Account ac : results) {
System.out.println(toString(ac));
if(e.getAcc_no() == ac.getAcc_no())
{System.out.println("Deserialized Account...");
System.out.println(toString(e));
}
}
}
And this is how I write them:
public void writeAccount(Account e) {
try {
ObjectOutputStream os1 = new ObjectOutputStream(
new FileOutputStream("test.txt", true));
os1.writeObject(e);
os1.close();
} catch (Exception exc) {
exc.printStackTrace();
}
}
Edit:
public void writeFile() {
for (int i = 0; i < accBank.size(); i++) {
writeAccount(retAcc(i));
}
}
Can any of you tell me what im doing wrong? I also tried other examples from other questions and didn't work.
What you're doing wrong is that you use several ObjectOutputStreams to write to the same file (which is not a txt file, BTW, since it contains binary data), and use a single ObjectInputStream to read all the accounts. As a consequence, a new serialization header is written each time you write an account, and the ObjectInputStream doesn't expect that.
The best way to write a list of accounts is to do just that: you store the accounts into a List<Account>, and write the list. To read the list of accounts, you do just that: you read a single object from the file, and cast it to List<Account>.

Can't create ObjectInputStream

Why can't I create an ObjectInputStream object? Every time I try to create one I get EOFException and I can't figure why. Can someone help me?
Below is the code with which I have the problem and the stack trace obtained from the execution. The file is empty.
public void loadFromFileStudent() throws IOException, ClassNotFoundException {
try{
InputStream inputStream = new FileInputStream("student.txt");
System.out.println(inputStream.toString());
ObjectInputStream objectInputStream;
objectInputStream = new ObjectInputStream(inputStream);
System.out.println(objectInputStream.toString());
this.repo=(Dictionary<Integer, Student>) objectInputStream.readObject();
objectInputStream.close();
inputStream.close();
}catch (EOFException e){
e.printStackTrace();;
//System.out.println(e.getMessage());
}
}
.
java.io.FileInputStream#65ddcac5
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2324)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2793)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:799)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at repository.Repository.loadFromFileStudent(Repository.java:94)
at repository.Repository.<init>(Repository.java:112)
at utils.DataStructure.createRepository(DataStructure.java:16)
at controller.Controller.<init>(Controller.java:9)
at utils.DataStructure.createController(DataStructure.java:20)
at application.RunMenu.<init>(RunMenu.java:15)
at application.App.main(App.java:5)
EOFException is thrown when end-of-file is reached. That is, you have read the whole file. Therefore you should not close your streams within the try statement, but use try-with-resources to automatically close them.
Try something simple like this:
public void loadFromFileStudent() throws IOException, ClassNotFoundException {
try (InputStream inputStream = new FileInputStream("student.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
this.repo = (Dictionary<Integer, Student>) objectInputStream.readObject();
} catch (FileNotFoundException e) {
System.out.println ("File not found");
} catch (IOException e) {
System.out.println ("Error while reading");
} catch (ClassNotFoundException e) {
System.out.println ("No class");
} catch (ClassCastException e) {
System.out.println ("Could not cast to class");
}
}
Writing is equally simple:
public void writeObject ( Object o ) {
try (FileOutputStream fos = new FileOutputStream ( this.filename );
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(o);
oos.flush();
} catch (NotSerializableException e) {
System.out.println ("Object wont be serialized");
e.printStackTrace();
} catch (IOException e) {
System.out.println ("Error while writing to file");
e.printStackTrace();
}
}
From my understanding of the question I assume OP is doing some thing like below, and which should works. May be OP would have missed something during writing/reading. Hope this helps to figure out.
public class Test2 {
public static void main(String[] args) {
Test2 t = new Test2();
t.create();
t.read();
}
public void create(){
try{
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("D:\\test\\ab.txt"));
Student st = new Student("chevs");
Dictionary<Integer, Student> dict = new Hashtable<Integer, Student>();
dict.put(1, st);
os.writeObject(dict);
}catch(Exception e){
e.printStackTrace();
}
}
public void read()
{
try{
InputStream inputStream = new FileInputStream("D:\\test\\a.txt");
System.out.println(inputStream.toString());
ObjectInputStream objectInputStream;
objectInputStream = new ObjectInputStream(inputStream);
System.out.println(objectInputStream.toString());
private Dictionary<Integer, Student> repo=(Dictionary<Integer, Student>) objectInputStream.readObject();
System.out.println(repo.get(1));
objectInputStream.close();
inputStream.close();
}catch (Exception e){
e.printStackTrace();;
}
}
public class Student implements Serializable{
public String name=null;
public Student(String name){
this.name=name;
}
public String toString() {
return name.toString();
}
}
}

why show me the last object i put in txt

I have a big problem , I write in a txt file same objects Accounts when i click to see all objects i have write in txt is show me the last one only and how i show up the account in JOptionPane , the second is how i can make the account to take nuber one ,two , three...... every account i write to take a number plus one from the precedent account .
I believ to explain apparent
if( str.equals("Receipt") )
{
ObjectInputStream in = null;
Account acc = null;
try
{
in = new ObjectInputStream(new FileInputStream("Accounts.txt"));
while( (acc = (Account) in.readObject()) !=null)
{
if (acc instanceof Account)
((Account)acc).print();
//acc.print();
}
}
catch(EOFException ex)
{
System.out.println("End of file reached.");
}
catch(ClassNotFoundException ex)
{
System.out.println("Error casting");
ex.printStackTrace();
}
catch(FileNotFoundException ex)
{
System.out.println("Error specified file does not exist");
ex.printStackTrace();
}
catch(IOException ex)
{
System.out.println("Error with I/O processes");
ex.printStackTrace();
}
finally
{
try
{
in.close();
}
catch(IOException ex)
{
System.out.println("Another IOException during the closing");
ex.printStackTrace();
}
}
}
code to write object in file
Account ac=new Account(posoOfil,poso,ariLoga,aitiol,diafor);
ac.print();
try{
OutputStream file = new FileOutputStream("Accounts.txt");
OutputStream buffer = new BufferedOutputStream( file );
ObjectOutput output = new ObjectOutputStream( buffer );
try{
output.writeObject(ac);
output.flush();
System.out.println("Object written to file");
}
finally{
output.close();
}
}
catch
(FileNotFoundException ex) {System.out.println("Error with specified file") ;
ex.printStackTrace();}
catch(IOException ex){
System.out.println("Cannot perform output.");
}
}
And the class Account
public class Account implements Serializable {
private int arithmKat;
// private Date date ;
private int posoOfil;
private int posoKat;
private String ariLoga ;
private String aitiol;
private boolean diafor=false;
public Account(int posoOfil, int posoKat,String ariLoga,String aitiol,boolean diafor){
arithmKat++;
this.posoOfil=posoOfil;
this.posoKat=posoKat;
this.ariLoga=ariLoga;
this.aitiol=aitiol;
this.diafor=diafor;
}
void print(){
System.out.println(arithmKat+" "+posoOfil+" "+posoKat+" "+diafor);}
}
You only write one account to the file. There is no loop at all in the code writing the account. Code that would write several accounts would look like this:
private void writeAccounts(List<Account> accounts) throws IOException {
OutputStream file = new FileOutputStream("Accounts.txt");
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
try {
for (Account account : accounts) {
output.writeObject(account);
}
output.close();
}
finally {
output.close();
}
}

Categories