Reading objects

I am writing a program where i have to read in a graph object.
I am not sure how to read in an object from a file though. I am trying to use an objectinputstream variable.readobject(). Is this right?

I am writing a program where i have to read in a graph
object.
I am not sure how to read in an object from a file
though. I am trying to use an objectinputstream
variable.readobject(). Is this right?Yes. And your graph object must be saved in the reverse -- ObjectOutputStream.writeObject().
--lichu

Similar Messages

  • Server hangs up when tryin to read object Urgent Help Plz

    Hi,
    I've been working on a client-server model for a while, I've tested my applicaction a thousand of times locally (I mean, server and serveral clients running on the same machine) and it's ok, now I finally run server in a remote host and I find it rarely works fine, most of the times server hangs up when tryin to read objects I dont know why.
    this is the part of the server-code where the problem begins:
    public int EscucharSocket(){
            Socket cliente = null;
            System.out.println("Servidor en escucha...\n");
            while(true){
                try{
                    cliente = SocketS.accept();
                    //I get client's ip and port
                    String ip = cliente.getInetAddress().getHostAddress();
                    int puerto = cliente.getPort();
                    //After the conexion is made, server reads a signature to
                    //identify the client
                   //in function process I check if the signature is valid
                   //SignedData is a class where I wrap the signiture (obviously
                   //it implements Serializable interface
                   process((SignedData)le.LeerObject(cliente));
                   //Other things done here
                catch (Exception e) { }
    }le is a class I use to read,write data to the socket, this is the code of the LeerObject function
    public Object LeerObject(Socket c) throws Exception {
           //Here Is where the server hangs up
            ObjectInputStream b = new ObjectInputStream(c.getInputStream());
            return b.readObject();
    }As I wrote when running locally, there is no problem, but when I have a remote host, that happens
    Any help or idea?

    Hi again, thnx for your help
    I modified my LE class so I just create a couple of Input/Output Streams per client (on server n client program), this is now the complete code of the class:
    import java.net.*;
    import java.io.*;
    public class LE {
        DataOutputStream     dos;
        ObjectOutputStream  oos;
        DataInputStream        dis;
        ObjectInputStream     ois;
        //Streams are created just once in the constructor
        public LE (Socket s) throws Exception {
            dos = new DataOutputStream(s.getOutputStream());
             //I'm not sure if this flush has any sense
            dos.flush();
            oos = new ObjectOutputStream (s.getOutputStream());
            oos.flush();
            dis = new DataInputStream(s.getInputStream());
            ois = new ObjectInputStream (s.getInputStream());
        public void EscribirByte(byte datos[],int len) throws Exception {
            dos.write(datos,0,len);
            dos.flush();
        public void EscribirString(String dato) throws Exception {
            dos.writeUTF(dato);
            dos.flush();
        public void EscribirChar(char dato) throws Exception {
            dos.writeChar(dato);
            dos.flush();       
        public void EscribirInt(int dato) throws Exception {
            dos.writeInt(dato);
            dos.flush();
        public void EscribirLong(long dato) throws Exception {
            dos.writeLong(dato);
            dos.flush();
        public void EscribirObject(Object dato) throws Exception {
            oos.writeObject(dato);
            oos.flush();
        public String LeerString() throws Exception {       
            return dis.readUTF();
        public int LeerInt() throws Exception {       
            return dis.readInt();
        public char LeerChar() throws Exception {       
            return dis.readChar();
        public long LeerLong() throws Exception {       
            return dis.readLong();
        public Object LeerObject() throws Exception {       
            return ois.readObject();
    }part of code of server and client, where the conexion is made and the LE object is created
    Server:
    try{
           cliente = SocketS.accept();               
           //After accepting the conexion the LE object is created
            le = new LE(cliente);
            //I get client's ip and port
            String ip = cliente.getInetAddress().getHostAddress();
            int puerto = cliente.getPort();
            //Object wraping signature is read        
            process((SignedData)le.LeerObject());
            //other control operations doing here
            //A thread is created to receive requests from client
            //(reference to LE object is passed to the thread
           ConexionCliente c = new ConexionCliente (cliente,id_persona,id_grupo,tipo_usuario,backup,le);                               
            //thread is started
            c.start();
    catch (Exception e) {
        try {
            cliente.close();
        catch(Exception e2){}
    }Cliente code:
    try{
       //it connects to the server
       c=new Socket(host,puerto);
       //After accepting the conexion the LE object is created         
       le = new LE(c);
       //other things made here to genarate SignedData Object
      //It sends signed data object
      le.EscribirObject(Data);          
      //A thread is created and started to receive messages from server
      //reference to object LE is sent to the thread to avoid the need of
      //creating another
      new ConexionServidorClient(c,id_persona,ci,le).start();
      return 1;
    catch(Exception e) {
       return -1;
    }after the change, itworks a little better, but still most of the times server hangs up, I can't make server operational yet and I dont have any idea for solving this issue

  • Problem reading objects

    Hi i am trying to read objects from i file i have written them to but cannot seem to get it goint any suggestions here are two errors but i am sure their are more
    ---------- javac ----------
    C:\university_class_work\cosc1309\Assignments\Assignment1\Bin2Text.java:26: incompatible types
    found : java.lang.Object
    required: java.io.ObjectInputStream
    while ((ins = ins.readObject()) != null) {
    ^
    C:\university_class_work\cosc1309\Assignments\Assignment1\Bin2Text.java:32: cannot resolve symbol
    symbol : method flush ()
    location: class java.io.ObjectInputStream
    ins.flush ();
    ^
    2 errors
    Normal Termination
    Output completed (1 sec consumed).
    import java.util.*;
    import java.text.*;
    import java.io.*;
    // Bin2Text.java
    // Assignment1
    // Created by dragon on Sun Mar 09 2003.
    // Copyright (c) 2003 __MyCompanyName__. All rights reserved.
    public class Bin2Text implements Serializable {
    public static void main(String[] args) throws IOException{
    String name;
    //PrintWriter out = null;
    Text2Bin p2b = new Text2Bin();
    StringTokenizer words = null;
    String line;
    try {
    PrintWriter out = new PrintWriter (new BufferedWriter (new FileWriter ("out.txt")));
    FileInputStream in = new FileInputStream ("in.bin");
    ObjectInputStream ins = new ObjectInputStream (in);
    while ((ins = ins.readObject()) != null) {
    PizzaEater myPizzaEater = new PizzaEater();
    ins.readObject(myPizzaEater);
    out.write (myPizzaEater);
    ins.reset ();
    ins.flush ();
    ins.close();
    out.close ();
    catch (IOException ioe) {
    System.out.println(ioe.getMessage());
    catch (NegativeNumberException nne) {
    System.out.println ("NegativeNumberException message was: " +
    nne.getMessage());
    class NegativeNumberException extends Exception {
    * Default constructor setting NegativeNumberException to the default
    * as specified by API reference Exception
    public NegativeNumberException () {
    super();
    * a Constructor passing the number value of the exception and
    * returning it with feedback
    public NegativeNumberException (int slices) {
    super("Number entered: " + slices + " number must be positive.");
    }

    Hi i am trying to read objects from i file i have
    written them to but cannot seem to get it goint any
    suggestions here are two errors but i am sure their
    are more
    ---------- javac ----------
    C:\university_class_work\cosc1309\Assignments\Assignmen
    1\Bin2Text.java:26: incompatible types
    found : java.lang.Object
    required: java.io.ObjectInputStream
    while ((ins = ins.readObject()) != null) {
    ^I'm not sure what you're trying to do exactly, I think its retrieve the next object from ObjectInputStream, you'd probably want to use another variable of type Object
    C:\university_class_work\cosc1309\Assignments\Assignmen
    1\Bin2Text.java:32: cannot resolve symbol
    symbol : method flush ()
    location: class java.io.ObjectInputStream
    ins.flush ();
    ^
    2 errors
    Normal TerminationNo flush() for InputStream objects.
    Output completed (1 sec consumed).
    import java.util.*;
    import java.text.*;
    import java.io.*;
    // Bin2Text.java
    // Assignment1
    // Created by dragon on Sun Mar 09 2003.
    // Copyright (c) 2003 __MyCompanyName__. All rights
    reserved.
    public class Bin2Text implements Serializable {
    public static void main(String[] args) throws
    ws IOException{
    String name;
    //PrintWriter out = null;
    Text2Bin p2b = new Text2Bin();
    StringTokenizer words = null;
    String line;
    try {
    PrintWriter out = new PrintWriter (new
    r (new BufferedWriter (new FileWriter ("out.txt")));
    FileInputStream in = new FileInputStream
    Stream ("in.bin");
    ObjectInputStream ins = new ObjectInputStream
    Stream (in);
    while ((ins = ins.readObject()) != null) {
    PizzaEater myPizzaEater = new
    Eater = new PizzaEater();
    ins.readObject(myPizzaEater);
    out.write (myPizzaEater);
    ins.reset ();
    ins.flush ();
    ins.close();
    out.close ();
    catch (IOException ioe) {
    System.out.println(ioe.getMessage());
    catch (NegativeNumberException nne) {
    System.out.println ("NegativeNumberException
    xception message was: " +
    nne.getMessage());
    class NegativeNumberException extends Exception {
    * Default constructor setting
    ing NegativeNumberException to the default
    * as specified by API reference Exception
    public NegativeNumberException () {
    super();
    * a Constructor passing the number value of the
    the exception and
    * returning it with feedback
    public NegativeNumberException (int slices) {
    super("Number entered: " + slices + " number must
    st be positive.");

  • Write / read objects to/from File

    Hello,
    I have a problem with the writing and reading objects to/from a file.
    So what excatly I'm trying to is:
    I have a class Data. A thread creates constantly (until some limit) objects of this class Data.
    Once an object is created, is placed in a buffer (I wrote my own class DataBuffer extention of LinkedList).
    I have a limit on this buffer, so when the limit is reached, another thread starts getings objects from the buffer, writes them on the disk and removing them from the buffer.
    I'm putting the object always on the "top" and I'm reading them and removing always from the "bottom" of the buffer (FIFO).
    For writing the objects Data to the file, I'm using a FileOutputStream and ObjectOutputStream:
    I have something like that:
    FileOutputStream fos = new FileOutputStrea("file_name");
    ObjectOutputStream oos = new ObjectOutputStream(fos);after that I have this:
    while(size > i ){
                        try {
                             Data d = buff.getData();
                             //write to File
                             oos.writeObject(buff.getData());
                             oos.flush();
                             buff.removeData();
                             System.out.println("written data " + d);
                             i++;
                        } catch (IOException e) {
                             e.printStackTrace();
                   }here size is the limit for the buffer.
    So, when the size is equal to the total number of objects that were created and placed in the buffer, I have no problems with the writing/reading from the file.
    But if size is equal, for example, to the half of the total number of objects that were created, I have a problem.
    A more detailed exmple is:
    10 objects were created, the 10 objects were places to the buffer, a test was made and all the objects were written on the disk -> writing and reading are OK.
    if 10 objects were created, and I want to write 5 objects, and after that more 5, the first thing I remarqued is that the size of the file is different from the size of the file created by the first method. Second thing is when I'm reading from the file I can read only 5 objects and after that I have this exception:
    java.io.StreamCorruptedException : invalid type code : AC
    So ... is anyone has an idea why I have this problem?
    PS. For reading from the file I'm using another thread that executes this code:
    fis = new FileInputStream(readFile);
                        ois = new ObjectInputStream(fis);
                        while(true){
                             try{
                                  Data d = (Data)ois.readObject();
                                  System.out.println("data read " + d); //here I'm displaying the object that was read
                                  buff.putData(d);
                             }catch(EOFException e){
                                  break;
                        ois.close();
                        fis.close();
                   }catch (FileNotFoundException e) {
                        e.printStackTrace();
                   }catch(IOException e){
                        e.printStackTrace();
                   }catch (ClassNotFoundException e) {
                        e.printStackTrace();
                   }Regards,
    Anton
    PS. At present I'm writing first all the Data objects, and after that I'm trying to read from the file.
    Edited by: anton_tonev on Oct 5, 2007 4:14 AM

    Hello again :)
    Finally I found the solution :)
    In fact it is important to not to close the FileOutputStream and ObjectOutputStream until all the data was written on the disk.
    What I mean:
    in the begining of the program you have to open these two streams and write down the data that comes from somewhere.
    But you musn't close these streams before the final writing on the disk.
    It must look like this:
    1 Open file stream & opent object stream
    2 you're writing your all objects: one by one; 10 by 10 or as you wish ... but after each writing down you don't close the streams
    3 you already finished with the writing, (the end of your program), now you can close the streams.
    Unfortunatly I don't know why if I write the data and close the stream every time, after that it is impossible to append new data (with reopen the file)

  • How to continue to read Object from a file?

    At some program I write an object into a file. This program will be called again and again so that there are many objects which are saved to that file. And I write another program to read object from this file. I can read the first object but can not read the second. However if I delete the object in that file (using editplus, by manually) I can read the second. Because now the second object is the first object. (Delete first object).
    The exception when I read the second object is below:
    java.io.StreamCorruptedException: Type code out of range, is -84
         at java.io.ObjectInputStream.peekCode(ObjectInputStream.java:1607)
         at java.io.ObjectInputStream.refill(ObjectInputStream.java:1735)
         at java.io.ObjectInputStream.readObject(ObjectInputStream.java:319)
         at java.io.ObjectInputStream.readObject(ObjectInputStream.java:272)
         at LogParser.main(LogParser.java:42)
    Exception in thread "main" The read object from file program is below:
         public static void main(String[] args) throws Exception {
            FileInputStream fis = new FileInputStream(path + File.separator + "ErrorApp21config2.log");
            ObjectInputStream ois = new ObjectInputStream(fis);
            ErrorLog errorLog = (ErrorLog)ois.readObject();
            System.out.println(errorLog.getErrorDate());
            FIFData fifData = (FIFData)errorLog.getErrorDescription();
            CommRegistration commRegistration = (CommRegistration)
                                     fifData.getDataObject(FIFData.REGISTRATION_DATA);
            String ic = commRegistration.getPatient().getPatExtID();
            System.out.println(ic);
            CommQueue commQueue = (CommQueue) fifData.getDataObject(FIFData.QMS_DATA);
            String location = commQueue.getLocation();
            System.out.println(location);
            ois.readObject();  //will throw above exception
            fis.close();
         }Can anyone tell me how to continue to read object? Or I should do some special things when I write object into file?

    Thanks Jos.
    Perhaps you are correct.
    There are some code in a SessionBean to log an object. Write file code is below.
         private void logPreRegError(
              byte[] strOldFifData,
            byte[] strNewFifData,
              String requestID)
              throws TTSHException {
              if (requestID.equals(RequestConstants.ADMIT_PATIENT)){
                String runtimeProp = System.getProperty("runtimeproppath");
                FileOutputStream fos = null;
                   try {
                        fos = new FileOutputStream(
                            runtimeProp + File.separator + "Error.log", true);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    bos.write(strOldFifData);
                    bos.write(strNewFifData);
                    bos.flush();
                   } catch (FileNotFoundException e) {
                        log(e);
                   } catch (IOException e) {
                    log(e);
                   } finally{
                    if (fos != null){
                             try {
                                  fos.close();
                             } catch (IOException e1) {
                                  log(e1);
         }strOldFifData and strNewFifData are the byte[] of an object. Below is the code to convert object to byte[].
         private byte[] getErrorData(FIFData fifData, boolean beforeException, String requestID) {
            ErrorLog errorLog = new ErrorLog();
            errorLog.setErrorDate(new Date());
            errorLog.setErrorDescription(fifData);
            errorLog.setErrorModule("Pre Reg");
            if (beforeException){
                errorLog.setErrorSummary("RequestID = " + requestID +" Before Exception");
            }else{
                errorLog.setErrorSummary("RequestID = " + requestID +" After Exception");
              ByteArrayOutputStream baos = null;
              ObjectOutputStream oos = null;
              byte[] bytErrorLog = null;
              try {
                  baos = new ByteArrayOutputStream();
                   oos = new ObjectOutputStream(baos);
                  oos.writeObject(errorLog);
                  oos.flush();
                  bytErrorLog = baos.toByteArray();
              } catch (IOException e) {
                   log(e);
              } finally {
                if (baos != null){
                        try {
                             baos.close();
                        } catch (IOException e1) {
                             log(e1);
              return bytErrorLog;
         }I have two questions. First is currently I have got the log file generated by above code. Is there any way to continue to read object from log file?
    If can't, the second question is how to write object to file in such suitation (SessionBean) so that I can continue to read object in the future?

  • Read Objects EOF

    I am trying to read object from a file into a linked list, but i keep getting a EOFException when it reaches the eof, i have tred a while loop but still the exception gets thorw, whats the best way of stoping reading once eof is read without throwing the exception?
    boolean EOF = false;
    ObjectInputStream fin = new ObjectInputStream(new FileInputStream("test.dat"));
    while(!EOF)
    Record rec = (Record) fin.readObject();
    a.add(rec); //add to linked list

    i'm not understand why you don't want to use Exception
    you still can execute you other path of code even using exception
    example
    try
    .... //do something
      try
      .... read object code here
      catch (EOFException ex)
    ... your other code
    catch (Exception anyException)
    }

  • You do not have Authorization to read object 'xyz' Authorization Object

    Hi,
         I am getting the following warning message while executing the query "You do not have Authorization to read object 'xyz' Authorization Object".
         I created an Authorization object.Assigned it to the role and assigned the user to the role.
    Thanks

    Hi,
      I'm getting the same message, please if you find the origin of it, please let me know, If I find it, I'll let you know, ok?
       Thanks!!

  • Visa read object difference parity setting for PC and TPC2012 device

    Hello,
     we found some difference between application running in PC and runing in TPC2012 device.
    We tested modbus communication via RS485 (9600b/s, 8bits, parity even) between PLC(master) and TPC2012 (slave). We used Visa read object and set parity to Even via property node. From the PLC we sent request to device and in our application we only read the data from PLC and displayed it (8bytes) on sreen.
    If we tested the application on PC everything worked fine. But if we compiled application and ran it in TPC2012 device  the data was different (for example if I sent request from PLC to slave 05 03 00 01 00 01 crc crc on the TCP I saw 00 03 00 01 00 01 crc crc. The  crc on TPC wasn't equal to crc on PLC.
    We found that problem was in VISA read setiing for read data in TPC device. If we set parity to SPACE (instead of EVEN)  then we read data correctly.
    Modbus - Parity set for VISA read object:
    Master PLC (even) - PC (even) -> visa read - data are equal
    Master PLC (even) - TPC (even) -> visa read - data aren't equal
    Master PLC (even) - TPC (space)-> visa read - data are equal 
    PC: Win XP SP2, LabView 8.5 with LabView TP module 8.5.
    TPC2012: WinCE 5.0, NI visa 4.2, NI TPC Service 1.0.
    Best regards,
    Pavel Rucka.

    I just found out that the VI for the currentmeasurement with the keithley 6517a has the same error but still works fine. Now I also tried to adjust the serial data bit and parity settings via the VISA configure serial port function but still no improvements.

  • No authorization to read object "ABC" authorization object

    Hi,
      I created an authorization object and based on that i created a role.I assigned the workbook to role and also the users are added.
    when i tried to run the workbook,i am getting the below warning and no data appears in workbok.
    "No authorization to read object "ABC" authorization object".
    Thanks in advance
    karthick

    authorization object is created in BI 7.0 or 3.5?
    Please check whether the ABC object is authorization relevant or not.
    check the authorizations in the role for the other auth objects like S_RS_COMP, S_RS_COMP1, S_RS_MPRO and S_RS_ICUBE.
    These are related to query and workbook authorizations.
    Hope this would help you. if you are not succeed in these option. go to ST01 and trace the user id authorizations.

  • Blocking reading object from stream

    I have a thread that continually reads objects from the input stream, so I use the readObject() method. My problem is that it doesn't block when there is no input. it just throws exceptions and I cant find a way to check first if there's anything output from the other side of the stream so do a check. thank you!

    Sorry! My mistake! I was confused!

  • Cannot send and read objects through sockets

    I have these 4 classes to send objects through sockets. Message and Respond classes are just for
    trials. I use their objects to send ıver the network. I do not get any compile time error or runtime error but
    the code just does not send the objects. I used object input and output streams to send and read objects
    in server (SOTServer) and in the client (SOTC) classes. When I execevute the server and client I can see
    that the clients can connect to the server but they cannot send any objects allthough I wrote them inside the main method of client class. This code stops in the run() method but I could not find out why it
    does do that. Run the program by creating 4 four classes.
    Message.java
    Respond.java
    SOTC.java
    SOTServer.java
    Then execute server and then one or more clients to see what is going on.
    Any ideas will be appreciated
    thanks.
    ASAP pls
    //***********************************Message class**********************
    import java.io.Serializable;
    public class Message implements Serializable
    private String chat;
    private int client;
    public Message(String s,int c)
    client=c;
    chat=s;
    public Message()
    client=0;
    chat="aaaaa";
    public int getClient()
    return client;
    public String getChat()
    return chat;
    //*******************************respond class*****************************
    import java.io.Serializable;
    public class Respond implements Serializable
    private int toClient;
    private String s;
    public Respond()
    public Respond(String s)
    this.s=s;
    public int gettoClient()
    return toClient;
    public String getMessage()
    return s;
    //***********************************SOTServer*********************
    import java.io.*;
    import java.net.*;
    import java.util.Vector;
    //private class
    class ClientWorker extends Thread
    private Socket client;
    private ObjectInputStream objectinputstream;
    private ObjectOutputStream objectoutputstream;
    private SOTServer server;
    ClientWorker(Socket socket, SOTServer ser)
    client = socket;
    server = ser;
    System.out.println ("new client connected");
    try
    objectinputstream=new ObjectInputStream(client.getInputStream());
    objectoutputstream=new ObjectOutputStream(client.getOutputStream());
    catch(Exception e){}
    public void sendToClient(Respond s)
    try
    objectoutputstream.writeObject(s);
    objectoutputstream.flush();
    catch(IOException e)
    e.printStackTrace();
    public void run()
    do
    Message fromClient;
    try
    fromClient =(Message) objectinputstream.readObject();
    System.out.println (fromClient.getChat());
    Respond r=new Respond();
    server.sendMessageToAllClients(r);
    System.out.println ("send all completed");
    catch(ClassNotFoundException e){e.printStackTrace();}
    catch(IOException ioexception1)
    ioexception1.printStackTrace();
    break;
    Respond k=new Respond();
    sendToClient(k);
    }while(true);
    public class SOTServer
    ServerSocket server;
    Vector clients;
    public static void main(String args[]) throws IOException
    SOTServer sotserver = new SOTServer();
    sotserver.listenSocket();
    SOTServer()
    clients = new Vector();
    System.out.println ("Server created");
    public void sendMessageToAllClients(Respond str)
    System.out.println ("sendToallclient");
    ClientWorker client;
    for (int i = 0; i < clients.size(); i++)
    client = (ClientWorker) (clients.elementAt(i));
    client.sendToClient(str);
    public void listenSocket()
    try
    System.out.println ("listening socket");
    server = new ServerSocket(4444, 6);
    catch(IOException ioexception)
    ioexception.printStackTrace();
    do
    try
    ClientWorker clientworker=new ClientWorker(server.accept(), this);
    clients.add(clientworker);
    clientworker.start();
    catch(IOException ioexception1)
    ioexception1.printStackTrace();
    while(true);
    protected void finalize()
    try
    server.close();
    catch(IOException ioexception)
    ioexception.printStackTrace();
    //*************************SOTC***(client class)*********************
    import java.io.*;
    import java.net.Socket;
    import java.net.UnknownHostException;
    class SOTC implements Runnable
    private Socket socket;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    public void start()
    try
    socket= new Socket("127.0.0.1",4444);
    input= new ObjectInputStream(socket.getInputStream());
    output= new ObjectOutputStream(socket.getOutputStream());
    catch(IOException e){e.printStackTrace();}
    Thread outputThread= new Thread(this);
    outputThread.start();
    public void run()
    try
    do
    Message m=new Message("sadfsa",0);
    output.writeObject(m);
    Respond fromServer=null;
    fromServer=(Respond)input.readObject();
    }while(true);
    catch(NullPointerException e){run();}
    catch(Exception e){e.printStackTrace();}
    public SOTC()
    start();
    public void sendMessage(Message re)
    try
    Message k=new Message("sdasd",0);
    output.writeObject(k);
    output.flush();
    catch(Exception ioexception)
    ioexception.printStackTrace();
    System.exit(-1);
    public static void main(String args[])
    SOTC sotclient = new SOTC();
    try
    System.out.println("client obje sonrasi main");
    Message re=new Message("client &#305;m ben mesaj bu da iste",0);
    sotclient.sendMessage(re);
    System.out.println ("client gonderdi mesaji");
    catch(Exception e) {e.printStackTrace();}

    ObjectStreams send a few bytes at construct time. The OutputStream writes a header and the InputStram reads them. The InputStream constrcutor will not return until oit reads that header. Your code is probably hanging in the InputStream constrcutor. (try and verify that by getting a thread dump)
    If that is your problem, tolution is easy, construct the OutputStreams first.

  • Read Object Label

    Hi, I read object from my Java Card successfully. But how can I get the label / it's name/ of that object? When I select EF DODF I can read the number of data objects from FCI /FIle Control Information/, Tag 82 for LINEAR-TLV.
    The FCI from selecting the object is - 6f 13 80 02 02 24 82 01 01 83 02 57 01 86 06 01 01 01 ff ff 01.
    Tag 80 - file size 80 02 *02 24*
    Tag 83 - FID 83 02 *57 01*
    But how can I get the name /Label/ of the object?
    Thank you
    Edited by: Valentino on Sep 14, 2012 1:05 AM

    Hi,
    first I select the AID, then select the DODF, then :
    1. if I select the object file with new CommandAPDU(0x00, 0xA4, 0x00, 0x00, new byte [] {0x57, 0x01})
    //I get the FCI :
    6f 13 80 02 02 24 82 01 01 83 02 57 01 86 06 01 01 01 ff ff 01 (I use this because i read the size of the object from the FCI).
    2. if I select the object file with new CommandAPDU(0x00, 0xA4, 0x04, 0x00 )
    //I get ( I tried to format it as I understand it from GlobalPlatform Card Specification v2.2.1 ):
    6f 65
         84 08 a0 00 00 00 03 00 00 00
         a5 59 9f 65 01 ff 9f 6e 06 47 91 81 02 31 00
              73 4a
                   06 07 2a 86 48 86 fc 6b 01
                   60 0c
                        06 0a 2a 86 48 86 fc 6b 02 02 01 01
                   63 09
                        06 07 2a 86 48 86 fc 6b 03
                   64 0b
                        06 09 2a 86 48 86 fc 6b 04 02 15
                   65 0b 06 09 2b 85 10 86 48 64 02 01 03
                   66 0c 06 0a 2b 06 01 04 01 2a 02 6e 01 02Then I read the file in while loop with : // Read BINARY
    ResponseAPDU obj = ch.transmit( new CommandAPDU(0x00, 0xB0, offset, 0x00) );Well I am new to Java Card technology and I get confused while reading GlobalPlatform Card Specification, ISO 7816-4 and the documentation of JCOP.
    So, what am I doing wrong?

  • Error while reading objects from a file

    Below is a short code to explain the problem i am facing
    i have been working on the same for past one week i am facing exceptions while reading a file containing more than one objects
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    * @author sakshi
    public class Storingobject implements Serializable{
        int x,y;
        public void addObject()
            //Storingobject temp;
            ObjectOutputStream objOut=null;
            try {
                objOut = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("temp.dat")));//if i pass true as parameter in FileOutputStream it gives Stream Corrupted exception
            } catch (IOException ex) {
                Logger.getLogger(Storingobject.class.getName()).log(Level.SEVERE, null, ex);
            try {
                // while((temp=objOut.writeObject(o))!=null)
                objOut.writeObject(this);
                System.out.println("Saved..");
                objOut.close();
            } catch (IOException ex) {
                Logger.getLogger(Storingobject.class.getName()).log(Level.SEVERE, null, ex);
        public void readobject()
            int i=1;
            Storingobject temp;
            ObjectInputStream objIn=null;
            try {
                objIn = new ObjectInputStream(new BufferedInputStream(new FileInputStream("temp.dat")));
            } catch (IOException ex) {
                Logger.getLogger(Storingobject.class.getName()).log(Level.SEVERE, null, ex);
            try {
                while ((temp = (Storingobject) objIn.readObject()) != null) {
                    System.out.println("VAlues of object i++ :");
                    System.out.println("X: "+temp.x+"Y: "+temp.y);
            } catch (IOException ex) {
                Logger.getLogger(Storingobject.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Storingobject.class.getName()).log(Level.SEVERE, null, ex);
        public static void main(String args[])
            Storingobject o1=new Storingobject();
            o1.x=10;o1.y=15;
            o1.addObject();
            o1.readobject();
    }

    //if i pass true as parameter in FileOutputStream it gives Stream Corrupted exceptionI agree. You can't append to a file written with an ObjectOutputStream. You would have to read it all in, write it all out again and write the new object. You're better off keeping the file open while you still have objects to write to it.
    while ((temp = (Storingobject) objIn.readObject()) != null) {ObjectInputStream.readObject() only returns null if you wrote a null. If you're not writing nulls, the correct technique is to loop until you get an EOFException. I don't favour explicitly writing a null just to get around this as suggested above, as it means you can never write a null for any other purpose.

  • OCCI BUG! Error reading Objects which contain NULLS

    The original problem was that I couldn't retrieve a SDO_GEOMERTY object from a table. Using OCCI and the OTT utility I always got assertions and exceptions.
    Various people have already reported this problem (e.g. Hu Cao, "HELP!! operating SDO_GEOMETRY with OCCI" ).
    After several hours of testing I found the real problem: When ever an object contain NULLS the problem appears.
    Eg. the "occiobj"-demo works fine with the original data. However, after setting one value in a publ_address object to NULL
    eg. UPDATE publisher_tab SET publisher_id=11, publisher_add=publ_address( NULL , 'NEW YORK') WHERE publisher_id=11;
    the demo program crashes!!!
    After discovering this, I generated a SDO_GEOMERTY object containing no NULLS and suddenly my program was able to retrieve the object.
    Consequently there is only one big problem remaining:
    A valid SDO_GEOMERTY object has to have NULLS in it!!!!
    Comments please
    Johannes
    (I'm working with Win2K and the Oracle 9i Client. The bug appears in conjunction with both Oracle 8.1.7 and Oracle 9i)

    I downloaded the Oracle 9i Release 2 (9.2.0.1) Client for Win and there I have less problems to get objects which contain NULLs.
    Now if a standard-typed member (of an objects) is NULL, OCCI recognizes this correctly and the program never crashed again.
    However, there is one BUG remaining. If an object-typed member is NULL the program still crashes.
    Eg. if the SDO_POINT member (type MDSYS.SDO_POINT_TYPE) of an MDSYS.SDO_GEOMETRY object is NULL,
    the program crashes in the
    void sdo_point::readSQL(oracle::occi::AnyData& streamOCCI_)
    function (which was generated by the OTT utility). It seems that in function
    void sdo_point::readSQL(void ctxOCCI_)
    the streamOCCI_.isNull() command doesn't recognize that the sdo_point object is NULL.
    (see source code below)
    WITH THIS BUG YOU CANNOT GET A MDSYS.SDO_GEOMETRY OBJECT WITH OCCI!!!
    Has anybody solved this problem? Is there a bug fix?
    Thanks in Advance
    Johannes
    void sdo_point::readSQL(void ctxOCCI_)
    sdo_point *objOCCI_ = new(ctxOCCI_) sdo_point(ctxOCCI_);
    oracle::occi::AnyData streamOCCI_(ctxOCCI_);
    try
    if (streamOCCI_.isNull()) // <-- doesn't recognize that the object in NULL
    objOCCI_->setNull();
    else
    objOCCI_->readSQL(streamOCCI_); // <-- consequently the actual readSQL is called, which crashes...
    catch (oracle::occi::SQLException& excep)
    delete objOCCI_;
    excep.setErrorCtx(ctxOCCI_);
    return (void *)NULL;
    return (void *)objOCCI_;
    void sdo_point::readSQL(oracle::occi::AnyData& streamOCCI_)
    X = streamOCCI_.getNumber();
    Y = streamOCCI_.getNumber();
    Z = streamOCCI_.getNumber();

  • Reading Objects using NIO

    I having problems reading an object using NIO APIs. I am end creating an Object and pass it through a socket. When I retrieve the data from the input stream within the socket I initialize a ByteBuffer by allocating a length. The problem is that there is NO way of knowing what to allocate that ByteBuffer when reading in the object. Below is within a method that allows me to read information from the socket.
    //Allocate the length ByteBuffer.
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    //Read the data from the SocketChannel....PROBLEM IS WHAT IF I NEED TO DO MULTIPLE READS
    socketChannel.read(buffer);
    ///We will create a byte array from the ByteBuffer.
    byte[] b = buffer.array();
    //ByteArrayInputStream that we will create and put the byte array in.
    ByteArrayInputStream bis = new ByteArrayInputStream(b);
    //ObjectInputStream where we will use the ByteArrayInputStream.
    ObjectInputStream input = new ObjectInputStream(bis);
    //Object that we will read in.
    Object obj = input.readObject();
    //Message that we will end up receiving.     
    Message receivingMsg = null;
    //Once we have our Message we will end up closing the connection.
    bis.close();
    input.close();
    //We will clear the buffer.
    buffer.clear();
    //We will cast the object to a message object so
    //that we can end up sending it through the right
    //routine which will allow us to send a response
    //back to the client. *********SPECIAL Class that will cast our generic object into a Message Object.
    Message receivedFromClient = (Message) obj;
    //we will end up taking that message and returning it.
    Message returningMsg = communicate(receivedFromClient);
    //Here we will end up taking the Message and putting it into the ByteBuffer.          
    ByteBuffer bb = objectToOutputStreamByteBuffer(returningMsg);
    socketChannel.write(bb);
    ----The problem is if I have more data within that Object. I need to re-allocate the ByteBuffer object and read everything on that socket. I tried the following code but I really don't feel it will be optimized the best for performance. I guess my question is that should I even be using NIO in this situation or Blocking IO?
    Again, here is the code that will read multiple data from the socket until it is -1.
    //Here we will read the information we received by first allocating
    //a ByteBuffer object.
    ByteBuffer buffer1 = ByteBuffer.allocate(5);
    ByteBuffer buffer2 = ByteBuffer.allocate(0);
    //We will read the data from this object.
    while ((socketChannel.read(buffer1)) != -1) {
    //We will check the Buffers and then try to recreate a new ByteBuffer that will put the remaining
    //stuff within the buffer. NOT SURE IF THIS IS THE MOST EFFICIENT WAY OF DOING THIS
    //AND ACTUALLY DON'T HAVE THE CODE WORKING CORRECTLY. THIS IS WHERE I
    //NEED HELP ON THE CORRECT WAY TO DO THIS.
         if (buffer1.remaining() < buffer2.remaining()) {
              buffer1.flip();
              buffer2 = ByteBuffer.allocate(buffer1.remaining() + buffer2.remaining());
              System.out.println("tmp 2 Remaining : " + buffer2.remaining());
              //tmp.put(buffer2);
              //buffer2 = tmp;
              System.out.println("Buffer 2 Remaining : " + buffer2.remaining());
         buffer2.put(buffer1);
         buffer1.clear();
    //We will create a byte array from the ByteBuffer.                    
    byte[] b = buffer.array();
    //ByteArrayInputStream that we will create and put the byte array in.
    ByteArrayInputStream bis = new ByteArrayInputStream(b);
    //ObjectInputStream where we will use the ByteArrayInputStream.
    ObjectInputStream input = new ObjectInputStream(bis);
    //Object that we will read in.
    Object obj = input.readObject();
    //Message that we will end up receiving.     
    Message receivingMsg = null;
    //Once we have our Message we will end up closing the connection.
    bis.close();
    input.close();
    //We will clear the buffer.
    buffer2.clear();
    buffer1.clear();
    //We will cast the object to a message object so
    //that we can end up sending it through the right
    //routine which will allow us to send a response
    //back to the client.
    Message receivedFromClient = (Message) obj;
    //we will end up taking that message and returning it.
    Message returningMsg = communicate(receivedFromClient);
    //Here we will end up taking the Message and putting it into the ByteBuffer.          
    ByteBuffer bb = objectToOutputStreamByteBuffer(returningMsg);
    socketChannel.write(bb);
    Any help would be greatly appreciated.

    I use my own InputStream class overriding the two standard read functions read( byte[], index, length ) and read(). When you construct it pass in the channel you are reading from and read from the channel on demand. ie when a call to read comes in you read say 100 bytes from the channel. The call required only 80 so these are consumed and the other 20 are buffered. Another read call is made, this time for 50 bytes but we only have 20 buffered so another read of the channel is needed. It is up to you whether you break the contract of read( byte[], index, length ) to keep reading the channel until the full "length" is available, or handle this in your application code.
    Then because this class is InputStream you can wrap it up inside any stream you like such as the ObjectInputStream and the data will be serialized correctly.

  • 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

Maybe you are looking for