Você está na página 1de 4

A friendly place for programming greenhorns!

Big Moose Saloon


Search

Java FAQ | Recent Topics Register / Login

JavaRanch Java Forums Java I/O and Streams

Author

How can I read all objects in a file with ObjectInputStream?


posted Saturday, September 22, 2007 20:38

Danilo Dadonas Ranch Hand Joined: Aug 24, 2007 Posts: 59


I like...

Hi people. I saw an example in Head First - Java that some objects are read from a file w ith ObjectInputStream. It's like this:
view plain copy to clipboard print ?

01. 02. 03. 04. 05. 06. 07. 08.

ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:\customers.ser")); Customer cus1 = (Customer) in.readObject(); Customer cus2 = (Customer) in.readObject(); Customer cus2 = (Customer) in.readObject(); . . .

I need to do it in a loop (like for or w hile) because I don't now how many objects the file haves. Is it possible? How can I do it? Thanks. Dadonas

Dadonas<br /> <br />Don't gain the world and lose your soul. Stan James (instanceof Sidekick) Ranch Hand Joined: Jan 29, 2003 Posts: 8791

posted Saturday, September 22, 2007 22:15

Hi, w elcome to the ranch! Give it a try in a loop and see w hat happens w hen you try to read past the last object.
view plain copy to clipboard print ?

01. 02. 03. 04. 05.

while(true)
{ Object o = in.readObject(); objectList.add( o ); }

Hint: expect an exception. Note the exact exception class and look up the JavaDoc. BTW: It is kind of the ranch style to give you some hints and set you off to experiment. The more you find on your ow n the more you w ill remember. Have fun, let us know w hat you find!

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John C iardi

converted by Web2PDFConvert.com

Danilo Dadonas Ranch Hand Joined: Aug 24, 2007 Posts: 59


I like...

posted Monday, September 24, 2007 03:32

Hi friend Stan. Your hint w as my first idea but I w anted a professional opinion. Below the solution:
view plain copy to clipboard print ?

01. 02. 03. 04. 05. 06. 07. 08. 09.

public Collection loadCustomers(){


ArrayList<Customer> customers = null; while(trye){ try{ customers.add((Customer) in.readObject()); } catch (EOFException e){reutrn customers}; } }

Thanks for help me.


Stan James (instanceof Sidekick) Ranch Hand Joined: Jan 29, 2003 Posts: 8791 posted Monday, September 24, 2007 04:25

It looks from the doc that the library forces us to use try catch for normal expected logic. This is generally a pretty bad thing, but I don't see any other w ay. Anyone else?
posted Monday, September 24, 2007 14:06

Danilo Dadonas Ranch Hand Joined: Aug 24, 2007 Posts: 59


I like...

Stan, I think your hint is the unique w ay, but the class ObjectInputStream should have a method like hasNext(). Don't you think?

Joe Ess Bartender Joined: Oct 29, 2001 Posts: 7910


I like...

posted Tuesday, September 25, 2007 18:29

I'm not a fan of using exceptions to handle expected events, as is apparently the case w ith ObjectInputStream. W hat I usually do w hen faced w ith this situation is put all my objects in a collection and serialize the collection. Of course, w ith large numbers of objects this method could cause performance problems.

"blabbing like a narcissistic fool with a superiority complex" ~ N.A. [How To Ask Questions On JavaRanch] Danilo Dadonas Ranch Hand Joined: Aug 24, 2007 Posts: 59
I like...

posted Tuesday, September 25, 2007 19:45

Accurately, Joe. That's it!!! Thank you so much. Dadonas

Ernest Friedman-Hill author and iconoclast Marshal Joined: Jul 08, 2003 Posts: 23379
I like...

posted Tuesday, September 25, 2007 19:50

Note that a stream is a stream, and you don't have to restrict your stream to holding just serialized objects. You could, for example, w rite the number of objects to follow as a four-byte int first (using DataOutputStream, for example.) Then read that w ord before trying to read any objects from the stream.

[Jess in Action][AskingGoodQuestions] Stan James (instanceof Sidekick) Ranch Hand Joined: Jan 29, 2003 Posts: 8791

posted Tuesday, September 25, 2007 21:16

Neat! I suppose one could also put a delimiter or eof marker after each object if you don't know the number before you start w riting.
posted Tuesday, September 25, 2007 21:42

Danilo Dadonas Ranch Hand Joined: Aug 24, 2007 Posts: 59


I like...

Yeah, all ideas are w elcome, but in my case, serialize an array is the w ay. I'm serializing objects to a file then after insert them in Oracle in other desktop. I'm using DAO, then I have an Interface like the exemplo bellow : http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html
converted by Web2PDFConvert.com

I read the information from my Oracle, serialize the informatiion, send the file to the other desktop, unserialize the objects an insert in the other Oracle. I know it's not the best w ay, but they w ant it. One more time, very thanks.
Jim Yingst Wanderer Sheriff Joined: Jan 30, 2000 Posts: 18652 posted Tuesday, September 25, 2007 21:56

[Stan]: It looks from the doc that the library forces us to use try catch for normal expected logic. This is generally a pretty bad thing, but I don't see any other way. Anyone else? I usually w rite and read an int first, as EFH suggests. Or w rite a Collection or array of objects at once. But if you don't have them all in memory at the start, or don't know in advance how many objects there w ill be, you could also do something like this:
view plain copy to clipboard print ?

01. 02. 03. 04. 05. 06. 07. 08. 09. 10.

public class EndOfStreamSignal implements Serializable {}


...

while (true) {
Object obj = oos.readObject(); if (obj instanceof EndOfStreamSignal) break; list.add(obj); }

[Joe]: What I usually do when faced with this situation is put all my objects in a collection and serialize the collection. Of course, with large numbers of objects this method could cause performance problems. It could, but it's pretty much the same problem you'd have w ith any other technique suggested so far. The objects w ill all have to be in memory at once anyw ay, since the ObjectInputStream keeps a reference to everything it has deserialized so far. So there's no w ay you can save memory by processing one object and then discarding it, unless you close one stream and start a new one. W hich adds more overhead in various forms. And the memory used by an ArrayList of objects, or an array of those same objects, is generally pretty close to the memory used by the objects themselves. I tried serializing 1000 Integer objects in various forms to see how much space they took: ArrayList of Integers: 10125 bytes Integer[] array: 10112 bytes w riteInt(1000) follow ed by 1000 Integers: 10077 bytes 1000 Integers follow ed by an EndOfStreamSignal: 10105 bytes In the case of Integers I could have made it smaller by w riting ints instead, but the point w as to use a simple small object. For larger objects (or a larger number of objects, the type of container you use w ill matter even less (proportionately). [EFH]: Y ou could, for example, write the number of objects to follow as a four-byte int first (using DataOutputStream, for example.) Minor clarification - an ObjectOutputStream implements DataOutput, an interface also implemented by DataOutputStream. As a result, an ObjectOutputStream already has a w riteInt() method and many similar methods there's no need to use a DataOutputStream also. Likew ise ObjectInputStream has a readInt(), just like DataInputStream does. So w riting and reading ints as EFH suggests is extremely easy.

"I'm not back." - Bill Harding, Twister

More Java Memory Use all available memory with BigMemory for Enterprise Ehcache terracotta.org/bigmemory Help W/ Java Programming? Troubleshoot & Tune Java Apps W/ New Relic Pro. Download Free Trial! NewRelic.com/Java Download the White Paper Discover the Mobile Mass-Market Potential of the US Brew Base www.brewmp.com/content/resources
subject: How can I read all objects in a file w ith ObjectInputStream?

Threads others viewed de-serialization results in null values on large array, advice requested Is there a w ay to open .ser file? problems reading an object file Question about getting arraylist's size IOStreams - W riting & Reading to a File All times above are in your local time zone & format.The current ranch time (not your local time) is May 14, 2012 11:19:06.
converted by Web2PDFConvert.com

Contact Us | Powered by JForum |


Java Application
Design & Scale The Next Big Mobile App On Windows Azure. Try it Free!
www.windowsazure.com /free-trial

Copyright 1998-2012 Paul W heaton

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture

converted by Web2PDFConvert.com

Você também pode gostar