This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Murach's Python Programming and have Michael Urban and Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why is my array not getting read in correctly from my file?  RSS feed

 
Gabrielle Evans
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In one file, I save a TreeNode object, then an int, and then a byte array to a file named `huffmanTrial.huff`.
In another file I want to read in all three of those things and do work on them. I can read in the TreeNode just fine and the int, but when I get to reading in the byte array I get that it is of size zero. Is that saying that it doesn't exist? I am using `in.available()` after I read in the TreeNode and int so I can see how big I need to make my new byte array and I always get 0. Am I somehow saving the array wrongly or am I reading it in wrongly?

Here is where I save the objects:



And here is where I am trying to read all three things in


I get `Size of array: 0`
I know for sure that the array that I am saving is not empty because just two lines before I save it, I print its contents. What am I doing wrong?
 
Gabrielle Evans
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Figured it out! I just needed to write the array with write() instead of writeObject()!
 
Paul Clapham
Sheriff
Posts: 22185
38
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch, Gabrielle!

You're using the "available" method of the ObjectInputStream, which apparently doesn't do what you think it does. Read our FAQ page Available Doesnt Do What You Think It Does for more information about that.

But anyway there's no need to write the size of the byte array in the ObjectOutputStream. You just need to write the array. Then reading the array from the ObjectInputStream will automatically get the array and put it back the way it was. Preallocating the array is just a waste of time since the empty array you preallocate will be discarded and replaced by the object read from the stream.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!