Saving and loading serialized objects (StreamCorruptedException)

Hello,
I am relatively new to Serialization (coming to that, a bit new to Java too) and I am having a problem with the following:
I am saving a number of serialized objects (all of the same class) in a file using the following way (the method is called multiple times to save a list of TeamMember objects):
Note: TeamMember is a custom class.
public void addTeamMember(TeamMember p) {
            outputStream = new ObjectOutputStream( new FileOutputStream( "team.dat", true ) );
            outputStream.writeObject( p );
            outputStream.flush();
            outputStream.close();
            outputStream = null;
}Then I'm trying to retrieve the objects from the file and display them. The method used is the following (it will loop through the file until found or it throws an EOFException. Is using the EOFException good practice to search through the entire file?):
public TeamMember getTeamMember(String id) {
        TeamMember currentMember = null;
        try {
            boolean found = false;           
            inputStream = new ObjectInputStream( new FileInputStream( "team.dat" ) );
            while ( !found ) {
                currentMember = (TeamMember)inputStream.readObject();
                if ( currentMember.getId().equals( id ) )
                    found = true;
            } // end while
            closeInputFile();
            return currentMember;
        } // end try
        catch ( EOFException e ) { // end of file reached
            closeInputFile();           
            return null;
        } // end catch
        catch ( IOException e ) {
            closeInputFile();
            System.err.println( e.getMessage() );
            return null;
        } // end catch
    }Now as a test, I am adding 3 members with IDs 1, 2 and 3 respectively. Then I am calling getTeamMember three times with the different IDs. With ID "1", it works fine. When I give it ID 2, it gives an IOException with message "StreamCorruptedException: invalid type code: AC".
While tracing the program, I've seen that it always gives me that error when reading past the first object saved in the file.
Am I saving the objects in a wrong way, or reading them is done incorrectly?
Any help is much appreciated.
I hope I was clear enough, and that I posted in the correct forum.
Thanks in advance.
Andrew.

If that is so, might you hint me for a work around?
I want to append objects in a single file, then be able to find and read an object from the file.
Thanks again.
Andrew

Similar Messages

  • Saving and Loading specific properties of an Image

    Hey everyone. I'm currently in the process of developing a game which allows you to customize the color (hue) of your character via a slider. What I would like to happen is: Upon clicking either Accept or Play, it will save the current hue of the image, navigating back to that page will load what was previously saved (hue), as well as when starting the game, it will replace the standard graphic with the previously saved image.
    Below is the code I have right now that pertains to the image with a basic non-functioning properly saving and loading code:
    import flash.events.KeyboardEvent;
    // open a local shared object called "myStuff", if there is no such object - create a new one
    var savedstuff:SharedObject = SharedObject.getLocal("myStuff");
    Accept.addEventListener(MouseEvent.CLICK, SaveData);
    PlayBTN.addEventListener(MouseEvent.CLICK, LoadData);
    function SaveData(MouseEvent){
               savedstuff.data.username = Sliders.Dino.MovieClip // changes var username in sharedobject
               savedstuff.flush(); // saves data on hard drive
    function LoadData(event: MouseEvent)
               if(savedstuff.size>0){ // checks if there is something saved
               Sliders.Dino.MovieClip = savedstuff.data.username} // change field text to username variable
    // if something was saved before, show it on start
    if(savedstuff.size>0){
    Sliders.Dino.MovieClip = savedstuff.data.username}
    What I have above is only saving the actual image, which is inside a movie clip names Sliders.
    Below is the Class I am using that associates with the slider that changes the hue of "Dino".
    package
              import flash.display.Sprite;
              import fl.motion.AdjustColor;
              import flash.filters.ColorMatrixFilter;
              import fl.events.SliderEvent;
              public class Main extends Sprite
                        private var color:AdjustColor = new AdjustColor();
                        private var filter:ColorMatrixFilter;
                        public function Main():void
                                  /* Required to create initial Matrix */
                                  color.brightness = 0;
                                  color.contrast = 0;
                                  color.hue = 0;
                                  color.saturation = 0;
                                  /* Add Listeners function */
                                  addListeners();
                        private final function addListeners():void
                                  colorPanel.hueSL.addEventListener(SliderEvent.CHANGE, adjustHue);
                        private final function adjustHue(e:SliderEvent):void
                                  color.hue = e.target.value;
                                  update();
                        private final function update():void
                                  filter = new ColorMatrixFilter(color.CalculateFinalFlatArray());
                                  Dino.filters = [filter];
    Overall what I'm asking for is: How do I get it to save the current hue of an image by clicking a button, and then having that previously saved image be loaded upon reloading or clicking a button? To me, it doesn't seem like it should be too hard, but for some reason I can not grasp it.
    Thanks in advance for reading this and for any assistance you have to offer!

    This is the Class that you told me to use:
    package
              import flash.display.Sprite;
              import fl.motion.AdjustColor;
              import flash.filters.ColorMatrixFilter;
              import fl.events.SliderEvent;
              import flash.net.SharedObject;
              public class Main extends Sprite
                        private var color:AdjustColor = new AdjustColor();
                        private var filter:ColorMatrixFilter;
                        private var so:SharedObject;
                        public function Main():void
                                  color.brightness = 0;
                                  color.contrast = 0;
                                  color.saturation = 0;
                                  so = SharedObject.getLocal("myStuff");
                                  if (so.data.hue)
                                            color.hue = so.data.hue;
                                  else
                                            color.hue = 0;
                                  update();
                                  addListeners();
                        private final function addListeners():void
                                  colorPanel.hueSL.addEventListener(SliderEvent.CHANGE, adjustHue);
                        private final function adjustHue(e:SliderEvent):void
                                  color.hue = e.target.value;
                                  so.data.hue = color.hue;
                                  so.flush();
                                  update();
                        private final function update():void
                                  filter = new ColorMatrixFilter(color.CalculateFinalFlatArray());
                                  Dino.filters = [filter];
    And this is the FLA Code:
    import flash.events.KeyboardEvent;
    // open a local shared object called "myStuff", if there is no such object - create a new one
    var savedstuff:SharedObject = SharedObject.getLocal("myStuff");
    Accept.addEventListener(MouseEvent.CLICK, SaveData);
    PlayBTN.addEventListener(MouseEvent.CLICK, LoadData);
    function SaveData(MouseEvent)
              savedstuff.data.username = Sliders.Dino.MovieClip;// changes var username in sharedobject
              savedstuff.flush();
              // saves data on hard drive;
    function LoadData(event: MouseEvent)
              if (savedstuff.size > 0)
              {// checks if there is something saved
                        Sliders.Dino.MovieClip = savedstuff.data.username;
              }// change field text to username variable
    // if something was saved before, show it on start
    if (savedstuff.size > 0)
              Sliders.Dino.MovieClip = savedstuff.data.username;

  • Saving and Loading variables in a .txt file (Offline)

    I'm working a software we've done with Flash, but we'd want
    people to be able to save the variables they selected. We need them
    to be able to save the value of about 10 variables in a file on
    their desktop, and then be able to load that file again.
    Is it possible to do that without having to use php or stuff
    like that (that's why we want to make it an offline applications so
    we don't have to use php to be able to save files).
    I know Actionscript looks a lot like Javascript and with
    Javascript it's really easy to do, but all the saving functions are
    blocked in Flash for security reasons.
    If anyone knows how to do that, to simply save and load a
    .txt file, please let me know. If it would be possible also to
    change the .txt to whatever else it would be even better. The file
    can still be opened in Notepad but at least it looks a bit more
    professionnal to have our own extension. Again in Javascript or
    with a .bat file it's really easy to save variables to whatever
    type of file, even to non existing types, it simply creates a text
    file with an unknown ending.
    Thanks!

    I found a page that explains in a really easy way how to
    communicate with Javascript if the flash object is contained in an
    html page, but I couldn't find any page explaining how it works if
    it's not in an html page. On our side, before using the software
    we're creating we'll convert it to a .exe. How can we call a
    Javascript from that .exe since we can't incorporate the Javascript
    in the container since there isn't really a container... Is there a
    way to link to a Javascript (.js) that would be in the same folder
    as the .exe? Or would there be a way to incorporate the Javascript
    right into the .exe?
    Let me know if any of you have a solution for that.
    Thanks!
    http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Liv eDocs_Parts&file=00000342.html#wp126566

  • Need help in JAXP - saving and loading of XML

    i am new to JAXP so dunno how to write the codes to save and load a hub project to and from an XML stream ...so can any one help by posting some codes to guide me alonr... will be grateful to u...this is wat i have done ,can anyone help to complete it ..thank...urgently
    import java.util.*;
    public class Testvector
         private Vector m_vProcess;
         String strProjectName;
         public static void main(String[] args)
              TestVector pThis = new TestVector();
              pThis->WriteToXML(m_vProcess);
         public TestVector
              strProjectName ="Project1";
              m_vProcess = new Vector();               
              m_vProcess.add("Process1");
              m_vProcess.add("Process2");
         public void WriteToXML(Vector vProcess)
              //JAXP
              //write project element with attribute name
              //iterate through all the elements in vector m_vProcess
              //write process elements with name.
    <?xml version='1.0' encoding='utf-8'?>
    <!-- project -->
    <project>
    <!-- process -->
    <process type="all">
    <name>1st</name>
    </process>
    </project>
    can any one help?

    Choose Xerces2.4 to serialize the DOM object is an option.
    javac XercesTest.java -classpath xmlParserAPIs.jar;xercesImpl.jar;.
    java -classpath xmlParserAPIs.jar;xercesImpl.jar;. XercesTest test.xml
    below is the source file: XercesTest.java
    //JAXP
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    //APACHE SERIALIZE FUNCTION
    import org.apache.xml.serialize.*;
    class XercesTest
    public static void main(String[] args) throws Exception
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse( new File( args[0] ) );
    File f = new File( "copy_of_"+ args[0] );
    OutputFormat format = new OutputFormat("xml","UTF-8",true ) ;
    FileOutputStream fout = new FileOutputStream( f );
    XMLSerializer ser = new XMLSerializer(fout, format );
    ser.serialize( doc );
    maybe it's helpful
    land

  • Saving and loading images (png) on the iPhone / iPad locally

    Hi,
    you might find this helpful..
    Just tested how to save and load images, png in this case, locally on the i-Devices.
    In addition with a SharedObject it could be used as an image cache.
    Make sure you have the adobe.images.PNG encoder
    https://github.com/mikechambers/as3corelib/blob/master/src/com/adobe/images/PNGEncoder.as
    Not really tested, no error handling, just as a start.
    Let me know, what you think...
    Aaaaah and if somebody has any clue about this:
    http://forums.adobe.com/thread/793584?tstart=0
    would be great
    Cheers Peter
        import flash.display.Bitmap
         import flash.display.BitmapData
        import flash.display.Loader   
        import flash.display.LoaderInfo
        import flash.events.*
        import flash.filesystem.File
        import flash.filesystem.FileMode
        import flash.filesystem.FileStream
        import flash.utils.ByteArray;
        import com.adobe.images.PNGEncoder;
    private function savePic(){
        var bmp =  // Your Bitmap to save
        savePicToFile(bmp, "test.png")
    private function loadPic(){
         readPicFromFile("test.png")
    private function savePicToFile(bmp:Bitmap, fname:String){
           var ba:ByteArray = PNGEncoder.encode(bmp.bitmapData);
            var imagefile:File = File.applicationStorageDirectory;
            imagefile = imagefile.resolvePath(fname);
            var fileStream = new FileStream();
            fileStream.open(imagefile, FileMode.WRITE);
            fileStream.writeBytes(ba);
             trace("saved imagefile:"+imagefile.url)
    private function readPicFromFile(fname:String){
            var imagefile:File = File.applicationStorageDirectory;
            imagefile = imagefile.resolvePath(fname);
            trace("read imagefile:"+imagefile.url)
            var ba:ByteArray = new ByteArray();
            var fileStream = new FileStream();
            fileStream.open(imagefile, FileMode.READ);
            fileStream.readBytes(ba);
            var loader:Loader = new Loader();
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onPicRead)
            loader.loadBytes(ba);   
    private function onPicRead(e:Event){
        trace("onPicRead")
         var bmp:Bitmap = Bitmap(e.target.content)
         // Do something with it

    Are the movies transferred to your iPhone via the iTunes sync/transfer process but don't play on your iPhone?
    Copied from this link.
    http://www.apple.com/iphone/specs.html
    Video formats supported: H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second, Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; H.264 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Baseline Profile up to Level 3.0 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats.
    What are you using for the conversion? Does whatever you are using for the conversion include an iPod or iPhone compatible setting for the conversion?
    iTunes includes a create iPod or iPhone version for a video in your iTunes library. Select the video and at the menu bar, go to Advanced and select Create iPod or iPhone version. This will duplicate the video in your iTunes library. Select this version for transfer to your iPhone to see if this makes any difference.

  • Saving and loading control properties

    Quick question,
    Does anyone know of an "easy" way to save and load pre-defined appearences or "skins" for controls and indicators?
    I had hoped LV 8.0 did this in the property explorer, but having just checked it out, it doesn't seem to.
    I basically want to be able to define the appearance of indicators (XY
    graphs particularly) based on calling up either ini files or otherwise.
    I want to avoid writing a cumbersome cluster-based read and write
    routine for each and every type of control (Split into classes of
    course, but still.....)
    Shane.
    Using LV 6.1 and 8.2.1 on W2k (SP4) and WXP (SP2)

    Thanks tst
    I will add the link to my labview folder.  The property saver will be a useful feature and would be a great method to have added to all gi objects, like Gobject->SaveState(file) and Gobject->LoadState(File), this could be polymorphic and also include versioning information and even allow for some metadata about the object.  Here you could make skins of a vi and it would save all the objects in a standard form.
    Paul
    Paul Falkenstein
    Coleman Technologies Inc.
    CLA, CPI, AIA-Vision
    Labview 4.0- 2013, RT, Vision, FPGA

  • Example of Serialized objects and non-Serialized objects

    Hi,
    Can you please tell me some of eample of Serialized objects and nonserialized objects in java and j2ee.
    Thanks
    alex.

    sravan123 wrote:
    Serialised objects are File ,all Collection classes , subclasses of Throwable and subclasses of Number.
    Non-Serialised objects are Connection,DataSourrce,Resultset , Thread and MathYou forgot to log in as another user before answering your own question incorrectly for reasons I'm currently unable to fathom

  • How to speed up my saving and loading of a psd. file?

    Hi.
    My laptop's 1 TB hdd recently crashed and I replaced it with a 500 GB ssd and Photoshop loads now from 10-12 sec since i re installed Photoshop cc.
    Unfortunately, the time it takes to save and load psd files has increased dramatically (I'm comparing it to how it was with my normal hdd). It also, sometimes freezes a bit and then after about 10 sec it unfreezes.
    I have looked online for help, but have been unable to find anything that could really help me (or it just went over my head, as I am not very tech savvy).
    Any help would be greatly appreciated.
    If this has been discussed before, can someone please post the link for me.

    The rule of thumb I follow to figure out scratch space says to figure on 50 to 100 times the size of your largest file ever multiplied by the number of files you have open.  I have seen the scratch file exceed 800 GB once, an admittedly rare occurrence, but it often exceeds 200 GB when stitching large panoramas and the like.
    As an example—and stressing that I'm aware that others have even more scratch space than I do—I keep two dedicated, physically separate hard drives as my primary and secondary Photoshop scratch disks and a lot of GB free on my boot drive for the OS.  I also have 16 GB of RAM installed.
    Additionally, if you only have a single HD, i.e. your boot drive, you'd need it to be large enough to accommodate both the swap files of the OS as well as Photoshop's scratch.

  • Liquify Cursor disappears when Saving and Loading Mesh (CC 2014.2.2)

    Hello.
    I'm using Photoshop CC 2014.2.2 for Mac on a perfectly built hackintosh (Yosemite, i7-4770K, GTX770, Intuos5 L, 32Gb RAM, 2 monitors).
    The arrow cursor disappears randomly when dragged over the Save Mesh or Load Mesh dialogues. It's not that the arrow cursor disappears completely. Actually, instead of switching from liquify cursor to arrow cursor as it should, it stays a circle and I can see it behind the save/load mesh window. In order to make the arrow appear in front of the save/load mesh, I have to move it out of it, and carefully move it back in. If I drag the save/load mesh window to an area of the screen clear of the liquify filter window or to my second screen, the problem goes away.
    Also, when liquifying, the cursor is a little laggy, like at a low frame rate and behind my pen. I can liquify with no problem, but I can't remember if this is the way the liquify cursor behaves now that the it is GPU accelerated.
    All these problems go away if I disable "use graphics processor", but that's a no go for me. I have tried both OS X Default Graphic Driver and NVIDIA Web Driver, but it makes no difference.
    Any ideas?
    THANKS!

    I've noticed it happens particularly when the arrow touches any of the text input fields, among other ways I haven't identified yet. The save mesh and load mesh are the only dialogs across Photoshop on which this problem happens.
    Notice that the blue cursor drawn by me is where the cursor should be, and note that the liquify cursor can be seen behind the open mesh dialogue. In this case I have to draw the cursor outside of the open window, and drag it back in making sure I don't touch the search field.

  • Saving and loading plugin's settings by using SDK APIs.

    Hi All.
    I am trying to save and load plugin's settings, ex. dialog setting values and strings.
    OS platform is windows XP.
    First I programmed the way of using *.ini file.
    But that not appropriate for Macintosh.
    So, I like to know common way by using SDK's APIs.
    Development env. is VS2008 and Ai CS5 SDK.
    Thanks.

    Use AIPreferenceSuite (AIPreference.h)

  • Writing and  Reading serialized Objects

    [code=java]
    /*hey guys i'm new to java and i have been given an exercise to make a cd collection, write it into a file and read the data back to the program.
    the program is suppose to show you a menu to select from where you can add, delete, view sort, CD's when you add a CD it must be written to a file as an Object and when you want to view CDs or search for a CD the program must read the CD objects from the file they have been written to and must return a cd nam, artist and release date. the code looks like it is writing the Cd to a file but when i try to read (view or search for a cd from the file it gives an error null). so i think i'm note reading the right way.
    thank you for helping .
    import java.io.Serializable;
    public class cd implements Serializable {
         //creating attributes
              private String cdname = null;
              private double price = 0.0;
              private String artist =null;
              private int ratings =0;
              private String genre=null;
              private String releaseDate =null;
         // creating an Empty constructor
              public cd(){
              public cd (String cdname,double price, int ratings, String genre, String artist, String releaseDate){
              this.cdname=cdname;
              this.price=price;
              this.artist=artist;
              this.ratings=ratings;
              this.genre=genre;
              this.releaseDate=releaseDate;
              public String getGenre(){
                   return genre;
              public void setGenre(String genre){
                   this.genre =genre;
              public String getArtist(){
                   return artist;
              public void setArtist(String artist){
                   this.artist=artist;
              public String getName(){
              return cdname;
              public void setName(String cdname){
              this.cdname = cdname;
              public Double getPrice(){
              return price;
              public void setPrice(double price){
              this.price = price;
              public String getReleaseDate(){
              return releaseDate;
              public void setReleaseDate(String releaseDate){
              this.releaseDate = releaseDate;
              public int getRatings(){
              return ratings;
              public void setRatings( int ratings){
              this.ratings = ratings;
    import java.util.*;
    public class hipHopCollection {
    ArrayList<cd> list = new ArrayList <cd> ();
    EasyIn ei = new EasyIn();
         private cd invoke;
         private int b;
         public void load()
              System.out.println(" You Entered " + b + " To Add A CD ");
              invoke = new cd();
              System.out.println("Please Enter A CD Name ");     
              invoke.setName(ei.readString());
              System.out.println("Please Enter A CD Price");
              invoke.setPrice(ei.readDouble());
              System.out.println("Please Give Ratings For The CD");
              invoke.setRatings(ei.readInt());
              System.out.println("Please Enter A CD release date ");
              invoke.setReleaseDate(ei.readString());
              System.out.println("Please Enter artist Name ");
              invoke.setArtist(ei.readString());
              System.out.println("Please Enter A CD Genre ");
              invoke.setGenre(ei.readString());
              list.add(invoke); // trying to add cd information to invoke.
         }// end of load
    // The following method should return the Object variable invoke that holds the cd INFO
         public Object getInvoke()
         return invoke;
         public int getB()
         return b;
         public void setB()
         b=ei.readInt();
         public void menu(){
              System.out.println("......................................................... ");
              System.out.println("Hi There Please Enter A Number For Your Choice");
              System.out.println(" Pess >>");
              System.out.println("1 >> Add A CD");
              System.out.println("2 >> View List Of CD's");
              System.out.println("3 >> Sort CD's By Price");
              System.out.println("4 >> Search CD By Name");
              System.out.println("5 >> Remove CD(s) By Name");
              System.out.println("0 >> Exit");
              System.out.println(".........................................................");
              System.out.print("Please Enter Chioce >> ");     
         }// end of menu
         public void GoodBye()
              System.out.println(" You Entered " + b + " To exit Good_bye" );
              System.exit(0);
         }//end of GoodBye
         public void PriceSort()
              System.out.println(" You Entered " + b + " To Sort CD(s) By price ");
              Collections.sort(list, new SortByPrice());
              for(cd s : list)
              System.out.println(s.getName() + ": " + s.getPrice());
         }// end of PriceSort
         public void NameSearch()
                   System.out.println(" You Entered " + b + " To Search CD(s) By Name ");
                   System.out.println("Please Enter The Name Of The CD You Are Searching For " );
                   String search = ei.readString();
                   for(int i=0; i<list.size();i++){
                   if(search.equalsIgnoreCase(list.get(i).getName() )){
                   System.out.println(list.get(i).getName() + " " + list.get(i).getPrice() + " " + list.get(i).getRatings() + " " + list.get(i).getGenre() );
    }//end of NameSearch
         public void ViewList()
                   System.out.println(" You Entered " + b + " To view CD(s) By Name ");
                   for(int i=0; i<list.size();i++)
                   System.out.println(list.get(i).getName() + " " + list.get(i).getPrice() + " " + list.get(i).getRatings() + " " + list.get(i).getGenre() );
         }// end of ViewList
         public void DeleteCd()
                   System.out.println(" You Entered " + b + " To Delete CD(s) By Name ");
                   System.out.println("Please Enter The Name Of The CD You Want to Delete ");
                   String search = ei.readString();
                   for(int i=0; i<list.size();i++)
                   if(search.equalsIgnoreCase(list.get(i).getName() ))
                   System.out.println(list.get(i).getName());
                   list.remove(i);
         }// end of DeleteCD
         public static void main(String[] args) {
         //creating an Instance of EasyIn by object ei. Easy in is a Scanner class for reading
              EasyIn ei = new EasyIn();
              ArrayList<cd> list = new ArrayList <cd> (); // creating an array cd list
              hipHopCollection call = new hipHopCollection();
              ReadWrite rw = new ReadWrite();
                   while (true){
                   call.menu();
                   call.setB();
                   //b = ei.readInt();
                   if(call.getB()==0)
                        call.GoodBye();
                   if(call.getB()==1)
                        call.load();
                        rw.doWriting();// trying to write the cd object to a file
                   if(call.getB()==2)
                   rw.doReading();// trying to read the cd object from a file
                   //call.ViewList();
                   if(call.getB()==3)
                   call.PriceSort();
                   if(call.getB()==4)
                        call.NameSearch();
                   if(call.getB()==5)
                        call.DeleteCd();
         }// end of while
    }// end of main
    }// end of class
    // importing all the packages that we will use
    import java.io.ObjectInputStream;
    import java.io.FileInputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectOutputStream;
    import java.io.OutputStream;
    import java.io.Serializable;
    public class ReadWrite {
    // these are all the attributes
         private String FileName ="CdCollections.dat";     
         private OutputStream output;
         private ObjectOutputStream oos;
         private FileOutputStream fos;
         private File file;
         private FileInputStream fis;
         private ObjectInputStream ois;
         //creating an empty constructor
         public ReadWrite()
         // we could initialise all the attributes inside this empty constructor
         //creating a constructor with arguments of a file name.
         public ReadWrite(File file)
              this.file=file;
              try
                   //Use a FileOutputStream to send data to a file called CdCollections.dat
                   fos = new FileOutputStream(file,true);
                   Use an ObjectOutputStream to send object data to the
                   FileOutputStream for writing to disk.
                   oos = new ObjectOutputStream (fos);
                   fis=new FileInputStream(file);
                   ois = new ObjectInputStream(fis);
              catch(FileNotFoundException e)
                   System.out.println("File Not Found");
              catch(IOException a)
                   System.out.println(a.getMessage());
                   System.out.println("Please check file permissions of if file is not corrupt");
         }// end of the second constructor
         //the following lines of code will be the accessors and mutators
         * @return the output
         public OutputStream getOutput() {
              return output;
         * @param output the output to set
         public void setOutput(OutputStream output) {
              this.output = output;
         * @return the objStream
         public ObjectOutputStream getOos() {
              return oos;
         * @param objStream the objStream to set
         public void setObjStream(ObjectOutputStream objStream) {
              this.oos = oos;
         public File getFile() {
              return file;
         public void setFile(File file) {
              this.file = file;
         public FileInputStream getFis() {
              return fis;
         public void setFis(FileInputStream fis) {
              this.fis = fis;
         public ObjectInputStream getOis() {
              return ois;
         public void setOis(ObjectInputStream ois) {
              this.ois = ois;
         // the following lines of code will be the methods for reading and writing
    the following method doWriting will write data from the hipHopCollections source code.
    that will be all the cd information.
    Pass our object to the ObjectOutputStream's
    writeObject() method to cause it to be written out
    to disk.
    obj_out.writeObject (myObject);
         public void doWriting()
              hipHopCollection call = new hipHopCollection();
    //creating an Object variable hold that will hold cd data from hipHopCollections invoke
              Object hold = call.getInvoke();// THI COULD BE THE PART WHERE I MADE A MISTAKE
              ReadWrite stream = new ReadWrite (new File(FileName));
              try
              Pass our object to the ObjectOutputStream's
              writeObject() method to cause it to be written out to disk.
              stream.getOos().writeObject(hold);
                   stream.getOos().writeObject(hold);
                   stream.getOos().close();
                   System.out.println("Done writing Object");
              catch (IOException e)
                   System.out.println(e.getMessage());
                   System.out.println("Program Failed To Write To The File");     
              finally
                   System.out.println("The program Has come To An End GoodBye");
         }// end of method DoWriting
    The following method is for reading data from the file written by the above method named
    DoWriting
    // PLEASE NOT THIS IS THE METHOD THAT GIVES ME NULL EXCEPTION
         public void doReading()
         ReadWrite read = new ReadWrite(new File(FileName));
              try{
                   //System.out.println("I AM NOW INSIDE THE TRY TO READ");
                   Object obj = read.getOis().readObject();
                   System.out.println("tried reading the object");
                   cd c = (cd)obj; // trying to cast the object back to cd type
                   System.out.println("I have typed cast the Object");               
                   System.out.println(c.getName());
                   System.out.println(c.getGenre());
                   System.out.println(c.getArtist());
                   System.out.println(c.getPrice());
                   System.out.println(c.getRatings());
                   System.out.println(c.getReleaseDate());
                   read.getOis().close();
              catch(ClassNotFoundException e)
              System.out.println(e.getMessage());
              System.out.println("THE CLASS COULD NOT BE FOUND");
              catch(IOException e)
              System.out.println(e.getMessage());// null
              System.out.println("WE COULD NOT READ THE DATA INSIDE THE FILE");
         }//end of method doReading
    }// end of class ReadWrite

    Cross posted
    http://www.java-forums.org/new-java/59965-writing-reading-serialized-java-object.html
    Moderator advice: Please read the announcement(s) at the top of the forum listings and the FAQ linked from every page. They are there for a purpose.
    Then edit your post and format the code correctly.
    db

  • Saving and loading

    is my coding correct, because i cant seem to save or load. well i dont know if it saves, but when its loading it returns null.
    public void saveAttributes(String filename){
    try{
    FileOutputStream outputFile = new FileOutputStream(filename);
    ObjectOutputStream outData = new ObjectOutputStream(outputFile);
    outData.writeObject(this);
    outData.flush();
    outputFile.close();}
    catch (Exception e){
    System.out.println("Error Saving: "+e.getMessage());}
    public static void loadAttributes(String filename){
    try {
    FileInputStream inputFile = new FileInputStream(filename);
    ObjectInputStream inData = new ObjectInputStream(inputFile);
    Attribute attribute = (Attribute)inData.readObject(); //not sure about this line. Attribute is the class where these and other methods are located. the load and save methods are called from another class.
    catch (Exception e) {
    System.out.println("Error Loading: "+e.getMessage()); }
    }

    this caught my eye are you trying to save a object then load it ?

  • Saving and loading vector

    i made a program that drawshapes.
    i would like to add features like saving the vector of shapes that has been created when a user presses the save button.
    then loading those shapes when the load button is pressed.
    how do i do this?
    thanks for any help

    You can always add different kind of objects to Collection (Vector), send them to back end and retrieve, send it back to the front end.
    DO you want to save all this information in a database and retrieve them using Vector?? If this is the case then you need an identifier in the database for every Vector you create and use this ID for creating the Vector which u can send it to the front end again.

  • Saving and loading 1D array to/from file

    Hi,
    i have some problems with my NI application. for the first, i have case structure with two cases: true and false.
    FALSE: in this case i have a for loop with 100 samples. i catch signal from my DAQ (now just Simulate Signal) and what i want is to save it in a 1D array and at the end of the loop the COMPLETE array into one text file. Problem in my vi: just the values from the last iteration are saved.
    TRUE: now i have while loop. AT THE BEGINN of the loop i need to load my array from the file and not in the middle of the loop. Why? The data from the file are needed during the loop.
    thanx in advance
    Vedran Divkovic
    RUB GERMANY
    Attachments:
    Regelsystem.vi ‏1494 KB

    According to your code, what you are saving is an array of means (one from each iteration), and NOT the last iteration. If you want to keep the entire data, it would be a 2D array.
    Why are you generating an entire waveform at each iteration? Shouldn't you just generate one point?
    LabVIEW Champion . Do more with less code and in less time .

  • Saving and Loading a Scenario

    Hi Friends,
    I would like to know how a scenario will be saved in Dashboard,In the same way i want to load the saved scenario
    http://businessobjects.auc.com/ESRI2008/cd/Sample_files/Xcelsius_2008_Samples/Flash%20Samples/financial_analysis_calculator.swf
    Could you please explain me in details how to do it.if possible send me a sample .xlf file.
    Thanks
    Santhosh

    Hi,
    The Local Scenario will be saved as .SOL file on your local machine.
    Even though if you are running it on Infoview, when ever you save a scenario of your dashboard.
    It goes to  C:\Documents and Settings\<user>\Application Data\Macromedia\Flash Player\macromedia.com\support\flashplayer\sys
    and stores the data in a .SOL.
    The file name will be selected randomly, mosty it will be in numbers.
    Let me know if you need any other information.
    Regards,
    AnjaniKumar C.A.

Maybe you are looking for