Reading an Array of Objects from a .bin file!

Hey, at the moment I'm creating a program whereby I write a set of objects onto a bin file, in this case an array of objects with a String name/county, and int population/area.... I'm not trying to read it back from the bin file and encountering trouble! I've managed to get it working using plain objects, however I want to be able to read in arrays of objects. The file itself compiles, however during running I get this error
java.lang.NullPointerException
at RecordFiles.CoastalRead.main(CoastalRead.java:33)
at RecordFiles.__SHELL16.run(__SHELL16.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at bluej.runtime.ExecServer$3.run(ExecServer.java:774)
Here is the program itself,
import java.io.*;
public class CoastalRead {
    public static void main(String[] args) {
        CoastalTowns towns[] = new CoastalTowns[50];
          towns[0] = new CoastalTowns();
          towns[1] = new CoastalTowns();
          towns[2] = new CoastalTowns();
          towns[3] = new CoastalTowns();
          towns[4] = new CoastalTowns();
          String name, county;
          int population, area;
        try {
            FileInputStream fileIn =
                    new FileInputStream("CoastalTownsBin.bin");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            for (int i = 0; i < towns.length; i++){
             towns[i] =(CoastalTowns) in.readObject();
               System.out.println("Deserialized File...");
                   System.out.println("Name: " + towns.name);
          System.out.println("County: " + towns[i].county);
     System.out.println("Population: " + towns[i].population);
          System.out.println("Area: " + towns[i].area);
in.close();
fileIn.close();
} catch (IOException i) {}
catch (ClassNotFoundException c) {}
+I'd appreciate a fast reply!+ And if someone needs the writing class I've used, I can post it asap.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

CoastalTowns towns[] = new CoastalTowns[50];
towns[0] = new CoastalTowns();
towns[1] = new CoastalTowns();
towns[2] = new CoastalTowns();
towns[3] = new CoastalTowns();
towns[4] = new CoastalTowns();Why create an array with a size of 50 and then only fill 5 elements?
Why bother filling any elements at all when you are reading the objects from a file?
What happens if there are less than 50 objects in your file?
I will assume CoastalTowns holds info about a single town, so why is it pluralised? Do you have a class called Dog or Dogs, Chair or Chairs, Person or People?
} catch (IOException i) {}
catch (ClassNotFoundException c) {}DO NOT swallow exceptions. At the very least put in a call to printStackTrace so you know if/when an exception occurs.
I'd appreciate a fast reply!I typed as fast as I could but unfortunately I'm still and hunt and peck guy.

Similar Messages

  • Creating an arrays of objects from a class

    I was wondering does any one know how to create an array of objects from a class?
    I am trying to create an array of objects of a class.
    class name ---> Class objectArray[100] = new Class;
    I cant seem to make a single class but i need to figure out how to create an array of objects.
    I can make a normal class with Class object = new Class

    There are four lines of code in your for-loop that actually do something:
    for(index = 0; index < rooms.length; index++) {
    /*1*/  assignWidth.setWidth(Double.parseDouble(in.readLine()));
    /*2*/  rooms[index] = assignWidth;
    /*3*/  assignLength.setWidth(Double.parseDouble(in.readLine());
    /*4*/  rooms[index] = assignLength;
    }1.) Sets the width of an object, that has been instantiated outside the loop.
    2.) assigns that object to the current position in the array
    3.) Sets the width of a second object that has been instantiated outside the loop
    4.) assigns that other object to the current position in the array
    btw.: I bet you meant "assignLength.setLength(Double.parseDouble(in.readLine());" in line 3 ;)
    Since each position in an array can only hold one value, the first assignment (line 2) is overwritten by the second assignment (line 4)
    When I said "construct a new room-object and assign it to rooms[index]" I meant something like this:
    for(index = 0; index < rooms.length; index++) {
        Room aNewRoom = new Room();
        aNewRoom.setWidth(Double.parseDouble(in.readLine()));
        aNewRoom.setLength(Double.parseDouble(in.readLine());
        rooms[index] = aNewRoom;
    }1.) Constructs a new Object in every iteration of the for-loop. (btw: I don't know what kind of objects you're using, so this needs most likely modification!!)
    2.) set the width of the newly created object
    3.) set the length of the newly created object
    4.) assign the newly created object to the current position in the array
    -T-
    btw. this would do the same:
    for(index = 0; index < rooms.length; index++) {
        rooms[index] = new Room();
        rooms[index].setWidth(Double.parseDouble(in.readLine()));
        rooms[index].setLength(Double.parseDouble(in.readLine());
    }but be sure you understand it. Your teacher most likely wants you to explain it ;)

  • Can i return an Array of Objects from c++ to java ??

    hello all,
    Can i return an Array of Objects from c++ to java ??
    If so how is it possible ??
    regards,
    gautam

    I suggest you look into the JNI, Java Native Interface. The answer is yes.

  • Reading a PublicKey \ PrivateKey type from a txt file

    Hi,
    i want to read a PublicKey \ PrivateKey type from a txt file and input it into a method.
    How can i read the data from the file while keeping or converting back to PublicKey \ PrivateKey type?
    I'm working with the following:
    generate = KeyPairGenerator.getInstance("ECDSA", "FlexiEC");                              
    generate.initialize(ecParams, new SecureRandom());
    KeyPair keyPair = generate.generateKeyPair();
    ............continues
    **and then i write the keys to the a simple txt file.**
    thanks!
    Edited by: sk16 on Apr 8, 2010 10:03 PM

    So, if i work with the two above is it ok, like:
    generate = KeyPairGenerator.getInstance("ECDSA", "FlexiEC");
                   generate.initialize(ecParams, new SecureRandom());
                   KeyPair keyPair = generate.generateKeyPair();
                   // Pub. and Priv. key objects.
                   PublicKey publicKey = keyPair.getPublic();
                   PrivateKey privateKey = keyPair.getPrivate();
                   // Write keys to separate files.
                   FileOutputStream fos = new FileOutputStream(publicKeyFile);
                   fos.write(publicKey.getEncoded());
                   fos.close();
                   FileOutputStream fos1 = new FileOutputStream(privateKeyFile);
                   fos1.write(privateKey.getEncoded());
                   fos1.close();
    and then for example>>>
    DataInputStream in = new DataInputStream(
              new FileInputStream("publicKeyFile.txt"));
              byte[] encodedPublicKey = new byte[1024];
              in.read(encodedPublicKey);
              in.close();
              X509EncodedKeySpec encodedPublicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
              KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "FlexiEC");
              publicKey = keyFactory.generatePublic(encodedPublicKeySpec);

  • How to read a tab seperated data from a text file using utl_file

    Hi,
    How to read a tab seperated data from a text file using utl_file...
    I know if we use UTL_FILE.get_line we can read the whole line...but i need to read the tab separated value separately.....
    Thanks in advance...
    Naveen

    Naveen Nishad wrote:
    How to read a tab seperated data from a text file using utl_file...
    I know if we use UTL_FILE.get_line we can read the whole line...but i need to read the tab separated value separately.....If it's a text file then UTL_FILE will only allow you to read it a line at a time. It is then up to you to split that string up (search for split string on this forum for methods) into it's individual components.
    If the text file contains a standard structure on each line, i.e. it is a fixed delimited structure, then you could use external tables to read the data instead.

  • How to read the 'full resolution composite' from a .psd file?

    I'm working with 16-bit .psd files and have the "maximize compatibility" switch turned on in CS2. When a file is saved, a message box appears indicating that PS is generating a "full resolution composite." I'd guess this is stored in the .psd file somehow, because some of the 3rd party image viewers are able to display the image when the compatibility switch is used, but are unable to display the image otherwise.
    My question is: how can I read this full resolution composite from the .psd file outside of Photoshop?
    If this is the wrong forum to post this question, I'd appreciate it of you'd tell me a better place.
    Thanks,
    Dave H.

    As you guess, it is stored in the PSD, but only with the Maximise Compatibility switch. Without that switch, a dummy image is stored which has the text "This layered Photoshop file was not saved with a composite image.", in English, German, Japanese and French.
    My program
    psdparse extracts each layer in an 8-bit file as a PNG, and the merged image for both 8- and 16-bit files. That link is to a Subversion repository containing source code.

  • Formatted .data file, reading in and creating an array of objects from data

    Hi there, I have written a text file with the following format;
    List of random personal data: length 100
    1 : Atg : Age 27 : Income 70000
    2 : Dho : Age 57 : Income 110000
    3 : Lid : Age 40 : Income 460000
    4 : Wgeecnce : Age 43 : Income 370000
    and so on.
    These three pieces of data, Name,Age and Income were all generated randomly to be stored in an array of objects of class Person.
    Now what I must do is , read in this very file and re-create the array of objects that they were initially written from.
    I'm totally lost on how to go about doing this, I have only been learning java for the last month so anyone that can lend me a hand, that would be superb!
    Cheers!

    Looking at you other thread, you are able to create the code needed - so what's the problem?
    Here's an (not the only) approach:
    Create an array of the necessary length to hold the 3 variables, or, if you don't know the length of the file, create a class to contain the data. Then create an ArrayList to hold an instance of the class..
    Use the Scanner class to read and parse the file contents into the appropriate variables.
    Add each variable to either the array, or to an instance of the class and add that instance to the arraylist.

  • Is it possible to return an array of objects from a web service?

    I have been trying to do this for a while now, and I have come to the conclusion that it may be impossible. To demonstate what I want to do I enclose a simple java file [1]. I have deployed this with Axis 2 and I enclose the responce [2], it is obciously not wat I want.
    Is it porrible to do this? If so, how?
    Thanks for any help,
    [1]
    package org.impress;
    public class SampleObject {
         public SampleElement[] noParameters(){
              SampleElement[] retArray = new SampleElement[2];
              retArray[0] = new SampleElement();
              retArray[0].name = "one";
              retArray[0].value = "alpha";
              retArray[1] = new SampleElement();
              retArray[1].name = "two";
              retArray[1].value = "beta";
              return retArray;
         public class SampleElement {
              public String name;
              public String value;
    }[2]
    <ns:noParametersResponse>
         <ns:return type="org.impress.SampleObject$SampleElement"/>
         <ns:return type="org.impress.SampleObject$SampleElement"/>
    </ns:noParametersResponse>

    Hi
    Can anybody help me with the code of how to return a resultset from a web service. i have put the resultset data's in an object array and tried to return it, but in the client side no data comes ,,, i mean it is printed as null.... and plz tell me where to specify the return type of a object in the wsdl file....
    thanks..

  • Oracle ADF Mobile getting array of objects from webservice

    hi,
    i am trying to fetch a certain number of records using a webservice call and then storing in the SQLLite DB in the mobile.
    i understand i can create a data control using the webservice > then?
    my webservice returns an array of objects.
    how can i do that?
    regards,
    ad

    It's fairly easy.
    What I have done is created a WebService Controller (plain java class) which calls the methods (from the WS) programmaticly.
    Example :
    public class WSController {
        private final String WSDataControllerName = "ThisIsTheNameOfMyWebserviceDataControl";
        private List pnames ,ptypes ,params;
        public WSController() {
            super();
        public List getAllActioncodesFromWS()
           //start - WS empty params
            pnames = new ArrayList();
            params = new ArrayList();
            ptypes = new ArrayList();
            pnames.add("findCriteria");
            params.add(null);
            ptypes.add(Object.class);
            pnames.add("findControl");
            params.add(null);
            ptypes.add(Object.class);
            //end - WS empty params
            List actionCodes = new ArrayList();
            try
                GenericType result = (GenericType)AdfmfJavaUtilities.invokeDataControlMethod(WSDataControllerName, null, "findActioncodesView1",pnames, params, ptypes);
                if(result!=null)
                    for (int i = 0; i < result.getAttributeCount(); i++)
                        GenericType row = (GenericType)result.getAttribute(i);
                        Actioncode wd = (Actioncode)GenericTypeBeanSerializationHelper.fromGenericType(Actioncode.class, row);
                        actionCodes.add(wd);
            catch (AdfInvocationException e)
                e.getMessage();
            catch (Exception e)
                e.getMessage();
         return actionCodes;
        }I also defined a Pojo named Actioncode :
    Note that the attribute names are completly the same as the VO from the web service.
    public class Actioncode {
        String Actioncode,Descript1;
        public Actioncode() {
            super();
        public Actioncode(String Actioncode, String Descript1) {
            super();
            this.Actioncode = Actioncode;
            this.Descript1 = Descript1;
        public void setActioncode(String Actioncode) {
            this.Actioncode = Actioncode;
        public String getActioncode() {
            return Actioncode;
        public void setDescript1(String Descript1) {
            this.Descript1 = Descript1;
        public String getDescript1() {
            return Descript1;
    }Since the WS method returns a GenericType, you can 'convert' that object to an POJO.
    Read more about it here :
    http://adf4beginners.blogspot.be/2013/01/adf-mobile-how-to-iterate-over-all-rows.html
    I know the blog post is about iterating over rows in an iterator, but it's just to illustrate how you can work with the GenericType

  • Reading objects from a binary file works but crashes LabVIEW on exit

    I've been hunting for the source of some crashes on LabVIEW exit and I was finally able to track it down to this. In my application I wrap measurements into objects that I stream into a binary file during the inspection. In another application I read the file again to browse and analyze the measurements. All this seems to work just fine except that the reading part causes LabVIEW to crash once I close the IDE. Built applications don't report any crashes but I am afraid if it might still cause some instability or unexpected behaviour.
    The snippet below represents the writing and reading scheme I use and with which I am able to reproduce the problem every time. I attached the project for testing it.
    Parts from the internal warning report:
    #OSName: Windows 8.1 Pro N
    #AppName: LabVIEW
    #Version: 13.0f2 32-bit
    DWarn 0xEFBFD9AB: Disposing OMUDClass definition [LinkIdentity "Class 1.lvclass" [ My Computer] even though 1014 inflated data instances still reference it. This will almost certainly cause a crash next time we operate on one of them.
    Possible path leak, unable to purge elements of base #0
     The full log is also attached.
    Notes:
    Remember: the reading works without any problems, the crash after LabVIEW exit is what I'm concerned about
    Seems to only happen with classes/objects—not the default LabVIEW Object, though
    Prepending array size or different byte orders make no difference
    The writing is time critical, the reading is not, in case you wish to suggest other options
    Has anyone else run into this? Should I be concerned for the built applications or can this be simply ruled as an IDE problem?
    Solved!
    Go to Solution.
    Attachments:
    test_project.zip ‏16 KB
    lvlog.txt ‏5 KB

    Right off, if you say you can read and write lv objects, try casting your object as a lv object before saving it. The lv object is the ultimate parent of all classes.
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • Reading an object from a binary file

    i am writing objects into my binary file using printwriter class. i am able to write objects into the file but i am having problems reading the object from the file. is there any other way of going about it. i tried using the objectoutputstream and object input stream class. but i am getting run time errors coz of something to do with serialization
    i am storing records as a object into a binary file so that it is easy to seek my records

    Of course you have trouble reading objects after you wrote them with a PrintWriter.
    You should rather have fixed the Serialization errors: only objkects that implement Serializable correctly can be serialized.

  • Passing array of objects from java to oracle.

    Hi,
    We have the following structure in oracle.
    We have a nested table type of varchar2(50).
    type var_tab is table of varchar2(50);
    We have one object type with one member as varchar2 and another one as var_tab type.
    type attribute_obj is object(
    attrib_name varchar2(100)
    ,attrib_val var_tab
    Then we have table type of that object type,
    type table_tab is table of attribute_obj;
    Then we have one object type with one member as varchar2,another member as integer and another one as table_tab type.
    type prod_obj is object(
    pr_name varchar2(100), tb_flag integer
    ,pr_attrib table_tab
    Then we have table type of this object type,
    type prod_tab as table of prod_obj;
    So, the total structure is something like this;
    'OS','OS_NAME', 'Windows'
    'Linux'
    'UNIX'
    'OS_VERSION','XP'
    'RED HAT'
    'SOLARIS'
    so, basically we have
    x prod_tab:=prod_tab();
    x(3):=prod_obj('OS',0,table_tab(attribute_obj('OS_NAME',var_tab('Windows','Linux','UNIX')),attribute_obj('OS_VERSION','XP','RED HAT','SOLARIS'))));
    And this how we call the procedure ---
    all_prod_comb_pkg.sp_main(x)
    The procedure deifinition is -
    procedure sp_main ( p_prod_arr prod_tab);
    Please suggest a way so that we can implement the same structure in Java and then call the procedure using that array of objects.
    regards,
    Dipankar.

    Dipankar,
    There's a separate example of how to map Oracle OBJECTs to JDBC STRUCTs.
    Study that one and combine the two. Not difficult (in my opinion :-)
    Or search the JDBC forum for the words "STRUCT" and "ARRAY".
    (What, you want me to do your coding for you?)
    Good Luck,
    Avi.

  • Extracting Array of objects from web service

    After a couple days of head banging I now have a webservice
    call executing and I am trying to extract / create a class from the
    ResultEvent:
    If the xml returned from the web service is:
    <people>
    <person name="Mike" />
    <person name="Dave" />
    </people>
    and the class is:
    class Person
    public var Name:String;
    The result event is:
    private function doResults(result:ResultEvent):void
    // how do I create an array of Person objects from result, I
    would also like to know how to create a typed array something like
    class PersonList if possible. I just need the raw how to loop the
    result and set the values on the class
    Thanks,
    Mike

    Well I wound up with just trial and error until I got it
    working, Im sure this will be improved as I go, but it's enough to
    press on with the app for now, this code is in the result function
    and result is the ResultEvent wich appears to be an array of
    generic objects representing the objects returned by the service.
    This in no way uses FDS and is talking to a simple dotnet / asp.net
    web service.
    // here app is a singleton class for app level data it is
    bindable and is used to update the view which in this example is
    bound to a public var MyObjects which in this case is an
    ArrayCollection, I unbox to MyObject in a custom view control
    for (var s:String in result.result)
    m = new MyObject();
    m.ID = result.result[s].ID;
    m.Name = result.result[s].Name;
    m.Type = result.result[s].Type;
    app.MyObjects.addItem(m);
    It also appears that you should create the WebService one
    time, and store refrences to the methods during app startup, the
    methods are called Operations and it appears you set the result and
    fault events then call send on the operation to get the data.
    // store this in a singleton app class
    var ws:WebService = new WebService();
    ws.wsdl = "
    http://dev.domain.com/WebService.asmx?WSDL";
    ws.addEventListener("result",doResults);
    ws.addEventListener("fault",doFault);
    ws.loadWSDL();
    // this is the operation which is also stored in the
    singleton app class
    var op:AbstractOperation = ws.getOperation("GetModules");
    // elsewere in the app we get the operation refrence setup
    result and fault and call send, then copy the generic object into
    our cutom classes using the first chunk of code above
    op.addEventListener("result",doResults);
    op.addEventListener("fault",doFault);
    op.send();
    I thought I would post this as I could find no such example
    in the offline or online docs, If anyone has a better way or see's
    a problem please post.
    I hope helps others with non FDS service calls and I look
    forward to hearing comments.
    Thanks,
    Mike

  • Deserialize an array of objects from a web service

    Hi, I'm calling a webservice method which returns an array of
    objects (let's
    say classes called MyClass).
    I now want to define a class in actionscript called MyClass
    which matches
    the properties of the class defined in the web service
    (written in .NET),
    call the webservice method, and then deserialize the result
    in actionscript
    into an array of type MyClass.
    The code I have so far is:
    import mx.services.WebService;
    import mx.services.Log;
    var mylog:Log = new Log(Log.DEBUG);
    myLog.onLog = function(txt) {
    trace(txt);
    var ws:WebService = new WebService(wsc.WSDLURL);
    ws.onLoad = function(wsdl) {
    MyPendingCallObject =
    ws.CallTheWebServiceMethodWhichReturnsAnArrayOfMyClasses();
    MyPendingCallObject.onResult = function(result)
    trace(result);
    // HOW CAN I DESERIALIZE the result parameter into an Array
    of
    MyClass ???
    MyPendingCallObject.onFault = function(fault)
    trace('FAULT! ' + fault.faultCode + "," +
    fault.faultstring);
    // If the WSDL fails to load the onFault event is fired.
    ws.onFault = function(fault) {
    trace(fault.faultstring);
    TIA

    Hi,
    I posted a similar problem some time ago :
    http://www.adobe.com/cfusion/webforums/forum/messageview.cfm?forumid=15&catid=294&threadid =1221565&enterthread=y
    Do you find any solution to your problem ?
    Fabrice

  • Create File Object from a remote file

    Hi,
    I would like to know about how to create a new File object from a file in a remote machine, it is a web application, i have the remote route of the file, and if I need the ip of the remote machine, I would like to know how to get it too.
    File fileobject = new File(�What do I have to put here or before or whatever?);
    Thank you very much.
    J.

    First, from the technical point of view you can't create a File object unless it's a file on the computer where the code is running. It doesn't matter if you have an IP address or something, if you haven't mapped a drive to it you can't create a File object.
    But more importantly, you can't just reach out from your server and grab a file from the client's computer. That's an obvious security violation and if you didn't realize that you shouldn't be designing web applications yet. If you want a file uploaded then you have to provide the client with an HTML form where they select a file to be uploaded.

Maybe you are looking for