ObjectInputStream JXTA problem

I'm trying to read an object from an ObjectInputStream (created from a JxtaSocket) like this:
Object obj = ois.readObject();
If the object is a String Object everything works just fine!
If the object for example is an ImageIcon, Integer or a custom object that is serializable I get a:
java.io.StreamCorruptedException
     at java.io.ObjectInputStream.readObject()
what is wrong ?

and this is the client related stuff ,
the problem accures in the out.writeObject(t) ,
i have an SocketException , and it says :
"socket write error ".
what can it be ?
public void init(){
     t=new Merkava();//temp , for checking
     System.out.println("Client: initializing");
     try{
       addr=InetAddress.getByName("localhost");
    }catch(IOException e){System.out.println("Client: unable to recieve address");}
     try{
         s=new Socket(addr,Server.PORT);
    }catch(IOException e){System.out.println("Client: unable to create socket");}
     try{
         out=new ObjectOutputStream((s.getOutputStream()));
    }catch(IOException e){System.out.println("Client: unable to create outputstream");}
     try{
      recv=new RecieveData(s);
    }catch(IOException e){System.out.println("Client: unable to create inputstream");}
   System.out.println("Client: initializing finished");
   public void start(){
     try{
       out.writeObject(t); //registers the tank in the server
     //  System.out.println("Client: registerd tank");
//THE PROBLEM ACCURES HERE!!!!!!    
}catch(IOException e){
           System.out.println("Client: unable to send data");}
         if(runner==null){
         runner=new Thread(this);
         runner.start();
   }

Similar Messages

  • ObjectOutputStream/ObjectInputStream/Socket Problem

    I make request on a server with socket connection.
    I want to use one socket open connection.
    So, I don't close the socket.
    This is like that :
    public void serverConnection()
    try
    DataOutputStream out = new DataOutputStream(s.getOutputStream());
    ObjectOutputStream objectOutStream = new ObjectOutputStream(out);
    objectOutStream.writeObject(configConnection);
    DataInputStream in = new DataInputStream(s.getInputStream());               
    ObjectInputStream objectInStream = new ObjectInputStream(in);
    arrayBlocks = (BFTransactionBlock[]) objectInStream.readObject();
    } catch (Exception e)
    valid = false;
    System.out.println("Error " + e);
    When I use this funtion more then one time with the same socket, the prorgam wait an the instruction :
    ObjectInputStream objectInStream = new ObjectInputStream(in);
    I use objectInStream.close() ...
    But it create an other problem : i lost the socket connection.
    What's the solution ?

    You don't need a new input stream for the same socket. You just need to read the data off of the original socket.
    DataInputStream in = new DataInputStream(s.getInputStream());
    ObjectInputStream objectInStream = new ObjectInputStream(in);The above code is fine. You need to loop through the code below until you are done with the socket. Then you close the socket. If you close the stream, you will close the underlying socket.
    arrayBlocks = (BFTransactionBlock[]) objectInStream.readObject();

  • How can I write new objects to the existing file with already written objec

    Hi,
    I've got a problem in my app.
    Namely, my app stores data as objects written to the files. Everything is OK, when I write some data (objects of a class defined by me) to the file (by using writeObject method from ObjectOutputStream) and then I'm reading it sequencially by the corresponding readObject method (from ObjectInputStream).
    Problems start when I add new objects to the already existing file (to the end of this file). Then, when I'm trying to read newly written data, I get an exception:
    java.io.StreamCorruptedException
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.readObject(Unknown Source)
    Is there any method to avoid corrupting the stream? Maybe it is a silly problem, but I really can't cope with it! How can I write new objects to the existing file with already written objects?
    If anyone of you know something about this issue, please help!
    Jai

    Here is a piece of sample codes. You can save the bytes read from the object by invoking save(byte[] b), and load the last inserted object by invoking load.
    * Created on 2004-12-23
    package com.cpic.msgbus.monitor.util.cachequeue;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    * @author elgs This is a very high performance implemention of Cache.
    public class StackCache implements Cache
        protected long             seed    = 0;
        protected RandomAccessFile raf;
        protected int              count;
        protected String           cacheDeviceName;
        protected Adapter          adapter;
        protected long             pointer = 0;
        protected File             f;
        public StackCache(String name) throws IOException
            cacheDeviceName = name;
            f = new File(Const.cacheHome + name);
            raf = new RandomAccessFile(f, "rw");
            if (raf.length() == 0)
                raf.writeLong(0L);
         * Whne the cache file is getting large in size and may there be fragments,
         * we should do a shrink.
        public synchronized void shrink() throws IOException
            int BUF = 8192;
            long pointer = getPointer();
            long size = pointer + 4;
            File temp = new File(Const.cacheHome + getCacheDeviceName() + ".shrink");
            FileInputStream in = new FileInputStream(f);
            FileOutputStream out = new FileOutputStream(temp);
            byte[] buf = new byte[BUF];
            long runs = size / BUF;
            int mode = (int) size % BUF;
            for (long l = 0; l < runs; ++l)
                in.read(buf);
                out.write(buf);
            in.read(buf, 0, mode);
            out.write(buf, 0, mode);
            out.flush();
            out.close();
            in.close();
            raf.close();
            f.delete();
            temp.renameTo(f);
            raf = new RandomAccessFile(f, "rw");
        private synchronized long getPointer() throws IOException
            long l = raf.getFilePointer();
            raf.seek(0);
            long pointer = raf.readLong();
            raf.seek(l);
            return pointer < 8 ? 4 : pointer;
         * (non-Javadoc)
         * @see com.cpic.msgbus.monitor.util.cachequeue.Cache#load()
        public synchronized byte[] load() throws IOException
            pointer = getPointer();
            if (pointer < 8)
                return null;
            raf.seek(pointer);
            int length = raf.readInt();
            pointer = pointer - length - 4;
            raf.seek(0);
            raf.writeLong(pointer);
            byte[] b = new byte[length];
            raf.seek(pointer + 4);
            raf.read(b);
            --count;
            return b;
         * (non-Javadoc)
         * @see com.cpic.msgbus.monitor.util.cachequeue.Cache#save(byte[])
        public synchronized void save(byte[] b) throws IOException
            pointer = getPointer();
            int length = b.length;
            pointer += 4;
            raf.seek(pointer);
            raf.write(b);
            raf.writeInt(length);
            pointer = raf.getFilePointer() - 4;
            raf.seek(0);
            raf.writeLong(pointer);
            ++count;
         * (non-Javadoc)
         * @see com.cpic.msgbus.monitor.util.cachequeue.Cache#getCachedObjectsCount()
        public synchronized int getCachedObjectsCount()
            return count;
         * (non-Javadoc)
         * @see com.cpic.msgbus.monitor.util.cachequeue.Cache#getCacheDeviceName()
        public String getCacheDeviceName()
            return cacheDeviceName;
    }

  • ObjectStreams

    Scenario: I have a Tomcat servlet engine running on a server.
    Tomcat is connected to a MySQL database.
    I have written an applet in Java which polls every 5 seconds (URLConnection)
    to a servlet. The servlet replies whether there are updates available. When there are
    updates available they get transmitted to the client. Think of thousands of objects that get transmitted to the client.
    The communication process all runs with (zipped) ObjectOutputStream and ObjectInputStream.
    Problem: The transfer speed is roughly in the beginning 1MB/s but the longer the client is connected and the more objects are streamed, the speed
    drops down to 400 KB/s. This happends out of the blue. Also why is 1MB/s a limit? Why not 10MB or 50MB?
    My question: Can someone summarize what steps Java does hardware-wise when using ObjectOutputStream and ObjectInputStream?
    I've read the API and know the technique behind object serialization and how Java handles this all.
    I am interested in knowing where the bottleneck lies. When I look at my CPU, it is barely in use. (10%).
    When I look at RAM, I notice -nothing- is swapping. Disk I/O isn't extraordinairy high as well..
    Finally as a sidenote, caching of ObjectStreams is unshared. Meaning objects arent cached.

    Im guessing you're aiming at HttpURLConnection.
    I'm not using that. Also not sure if that was an advise to start using it...
    I've decided to add some code to give an impression how it works.
        private URLConnection CreateConnection(URL urlServlet) throws IOException
            URLConnection connection = urlServlet.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/x-java-serialized-object");
            return connection;
    public static Poll doPollingRequest(URLConnection urlCon, Poll pollObj) throws ClassNotFoundException
            OutputStream outstream = null;
            Poll replyPoll = null;
            try
                outstream = urlCon.getOutputStream();
                GZIPOutputStream gout = new GZIPOutputStream(outstream);
                ObjectOutputStream oos = new ObjectOutputStream(gout);
                oos.writeObject(pollObj);
                oos.flush();
                oos.close();
                InputStream instr = urlCon.getInputStream();
                GZIPInputStream gin = new GZIPInputStream(instr);
                ObjectInputStream inputFromServlet = new ObjectInputStream(gin);
                replyPoll = (Poll) inputFromServlet.readObject();
                inputFromServlet.close();
                gin.close();
                instr.close();
            } catch (IOException ex)
                Logger.getLogger(Polling.class.getName()).log(Level.SEVERE, null, ex);
            } finally
                try
                    outstream.close();
                } catch (IOException ex)
                    Logger.getLogger(Polling.class.getName()).log(Level.SEVERE, null, ex);
            return replyPoll;
        }The doPollingRequest works with a "Poll" object. There are all kinds of objects that get streamed to update or alter the client after the client requests them.

  • A problem with ObjectInputStream

    I am a coding newbe and I recently tried to write a very simple app - an engine to send and recive objects through the net. This is what i get:
    //Serwer class:
    import java.net.*;
    import java.io.*;
    public class Serwer {
    public Serwer() {
    try {
    ServerSocket serw = new ServerSocket(23);
    System.out.println("Server up and running");
    while (true) {
    Socket soc = serw.accept();
    Obsluga obs = new Obsluga(soc);
    obs.start();
    catch (Exception e) {
    System.out.println(e);
    public static void main(String[] args)
    Serwer serwer = new Serwer();
    class Obsluga extends Thread {
    private Socket soc;
    public Obsluga(Socket soc) {
    this.soc = soc;
    public void run() {
    try {
    System.out.println("Connected from: " + soc.getInetAddress());
    ObjectOutputStream out = new ObjectOutputStream(
    new BufferedOutputStream(soc.getOutputStream()));
    //ObjectInputStream in = new ObjectInputStream(
    //new BufferedInputStream(soc.getInputStream()));
    //Here's the problem
    int i = 1;
    while(i<100) {
    Ob obiekt = new Ob(i,"text");
    out.writeObject(obiekt);
    i++;
    out.close();
    catch (IOException ex) {
    ex.printStackTrace();
    class Ob implements Serializable {
    private int number;
    private String text;
    public Ob(int number, String text) {
    this.number = number;
    this.text = text;
    public Ob() {
    public int getNumber() {
    return number;
    public String getText() {
    return text;
    public void setNumber(int i) {
    number = i;
    public void setText(String s) {
    text = s;
    //Client class:
    import java.io.*;
    import java.net.Socket;
    public class Klient {
    public Klient() {
    public static void main(String[] args) {
    ObslugaKlienta obsK = new ObslugaKlienta();
    obsK.run();
    class ObslugaKlienta extends Thread {
    public ObslugaKlienta() {
    public void run() {
    Ob obiektIn = new Ob();
    try {
    Socket socket = new Socket("localhost", 23);
    ObjectInputStream in = new ObjectInputStream(
    new BufferedInputStream(socket.getInputStream()));
    ObjectOutputStream out = new ObjectOutputStream(
    new BufferedOutputStream(socket.getOutputStream()));
    while (true) {
    obiektIn = (Ob) in.readObject();
    System.out.println(obiektIn.getNumber());
    catch(Exception e) {
    System.out.println(e);
    class Ob implements Serializable {
    private int number;
    private String text;
    public Ob(int number, String text) {
    this.number = number;
    this.text = text;
    public Ob() {
    public int getNumber() {
    return number;
    public String getText() {
    return text;
    public void setNumber(int i) {
    number = i;
    public void setText(String s) {
    text = s;
    The server class simply creates 100 Objects Ob and sends them to waiting Client, which prints the field number from it. And this works.
    The problem is, in my Serwer class, if I try to start new InputStreamReader, to receive Objects Ob from Client, the app stops working. Even if I am not using it anywhere. (u have to uncomment the declaration to see it - where "here is the problem" statment is)
    I think I am missing some theory about sockets. Can anyone clear me with it? And give me a working solution, what should I correct in my code to have both client and server able to exchange Objects?
    Im using jdk 1.6, and running both apps from a single machine.
    Thank you in advance.

    Thank you for the reply.
    I reworked my app: I moved sending and receiving to different Threads, but still I can not manage to get output i wanted to. I get the SocketClosed Exception.
    Server:
    package pakiet;
    import pakiet.Send;
    import pakiet.Receive;
    import java.net.*;
    import java.io.*;
    public class Serwer {
    public Serwer() {
    try {
    ServerSocket serw = new ServerSocket(23);
    System.out.println("Server up and running");
    while (true) {
    Socket soc = serw.accept();
    Obsluga obs = new Obsluga(soc);
    obs.start();
    catch (Exception e) {
    System.out.println(e);
    public static void main(String[] args)
    Serwer serwer = new Serwer();
    class Obsluga extends Thread {
    private Socket soc;
    public Obsluga(Socket soc) {
    this.soc = soc;
    public void run() {
    System.out.println("Connection from: " + soc.getInetAddress());
    new Receive(soc).start();
    new Send(soc).start();
    Client:
    package pakiet;
    import pakiet.Send;
    import pakiet.Receive;
    import java.io.*;
    import java.net.Socket;
    public class Klient {
    public Klient() {}
    public static void main(String[] args) {
    ObslugaKlienta obsK = new ObslugaKlienta();
    obsK.start();
    class ObslugaKlienta extends Thread {
    public ObslugaKlienta() {}
    public void run() {
    try {
    Socket socket = new Socket("localhost", 23);
    new Receive(socket).start();
    new Send(socket).start();
    catch(Exception e) {
    System.out.println(e);
    Send:
    package pakiet;
    import java.io.BufferedOutputStream;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    class Send extends Thread {
    Socket socket;
    public Send(Socket socket) {
    this.socket = socket;
    public void run() {
    try {
    System.out.println("Thread Send activated");
    ObjectOutputStream out = new ObjectOutputStream(
    new BufferedOutputStream(socket.getOutputStream()));
    int i = 1;
    while(i<10) {
    Ob obiekt = new Ob(i,"tekst");
    out.writeObject(obiekt);
    sleep(100);
    i++;
    catch(Exception e) {
    System.out.println(e);
    Receive:
    package pakiet;
    import java.io.BufferedInputStream;
    import java.io.ObjectInputStream;
    import java.net.Socket;
    class Receive extends Thread {
    Socket socket;
    public Receive(Socket socket) {
    this.socket = socket;
    public void run() {
    try {
    System.out.println("Thread Receive activated");
    ObjectInputStream in = new ObjectInputStream(
    new BufferedInputStream(socket.getInputStream()));
    int i = 1;
    while(i<10) {
    Ob obiekt = (Ob) in.readObject();
    System.out.println(obiekt.getNumber());
    sleep(500);
    i++;
    catch(Exception e) {
    System.out.println(e);
    My goal is to receive Ob numbers simultaneously in both server and client output window. Now i got massage in both client and sever that Thread Send and Receive is activated, but nothing happends afterwards.
    I know its a lot of code, so I bolded the parts I consider most important.

  • ObjectInputStream problems

    Hi
    I'm getting slightly desperate after 3 days stuck with the same problem.
    I'm writing a small client server application that contains a chat room. when I use a printwriter combined with a BufferedReader on the sockets everything works perfectly.
    However, I need to send objects to keep a state for some additinbal functionality, and when I change the printwriter/BufferedReader to a ObjectOutputStream/ObjectInputStream I keep getting a StreamCorruptedException on the client.
    It goes like this. As long as I keep sending objects from the server, the client receives them well, but as soon as the server stop sending (waiting for som GUI interaction) I get the exception. As I understand it, the program is supposed to wait at the in.readUTF(); line and then continue when it receives data, but it doesn't wait. It just throws an exception as soon as it stops receiving data.
    I don't think it has anything to do with the read method. Apparently it is the ObjectInputStream complaing when receiving no data.
    Does anyone have an explanition for this?

    I'm not sure exactly how you're "changing the printwriter/BufferedReader to a ObjectOutputStream/ObjectInputStream", but the problem is probably that you're sending binary data (ObjectOutputStream) into a text stream (PrintWriter). If you need to send both binary and text data, then I think you will have to set up two sets of streams.

  • ObjectInputStream problem.

    Hello!
    I have a problem with ObjectInputStream.
    My Servlet code is:
    public class MyServlet extends HttpServlet {
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    ObjectInputStream inputFromApplet = new ObjectInputStream(request.getInputStream());
    When I call it, I get "The page cannot be displayed".
    But when I write
    InputStreamReader inputFromApplet = new InputStreamReader(request.getInputStream());
    instead, the page is displayed(showing nothing, of cause).
    It doesn't matter whether I call the servlet from applet or from browser. Anyway, here is a part of my Applet code:
    URL DownloadFileServlet = new URL( servletGET );
    URLConnection servletConnection = DownloadFileServlet.openConnection();
    // inform the connection that we will send output and accept input
    servletConnection.setDoInput(false);
    servletConnection.setDoOutput(true);
    // Don't use a cached version of URL connection.
    servletConnection.setUseCaches (false);
    servletConnection.setDefaultUseCaches (false);
    servletConnection.setRequestProperty
    ("Content-type", "application/octet-stream");
    ObjectOutputStream outputToServlet =
    new ObjectOutputStream(servletConnection.getOutputStream());
    String str = "abc";
    outputToServlet.writeObject(str);
    outputToServlet.flush();
    outputToServlet.close();
    Please help me.
    Thank you in advanse.

    Already posted in another forum.

  • Problem with JXTA Application P2P

    Hi, to all
    From this site:
    http://www.brendonwilson.com/projects/jxta/
    i have download the "chapter10" in 2Source Code" area,
    this code, implements JXTA library for simple application that execute an exponential math.
    But i have a problem to execute it because i have an exception when i luonch the main class (ExampleServiceTest):
    With a tracking of exception, my output is:
    <INFO 2005-09-12 21:04:07,515 NullConfigurator::<init>:146> JXTA_HOME = C:\Documents and Settings\Mirko\Desktop\PROTOTIPO JXTA\Eclipse\tempo\.jxta
    <INFO 2005-09-12 21:04:07,531 NullConfigurator::resetFromResource:362> C:\Documents and Settings\Mirko\Desktop\PROTOTIPO JXTA\Eclipse\tempo\.jxta\PlatformConfig already exists
    <INFO 2005-09-12 21:04:07,531 NullConfigurator::resetFromResource:362> C:\Documents and Settings\Mirko\Desktop\PROTOTIPO JXTA\Eclipse\tempo\.jxta\jxta.properties already exists
    <INFO 2005-09-12 21:04:07,765 NullConfigurator::adjustLog4JPriority:441> Log4J [user default] requested, not adjusting logging priority
    <INFO 2005-09-12 21:04:12,437 NullConfigurator::adjustLog4JPriority:441> Log4J [user default] requested, not adjusting logging priority
    net.jxta.exception.ServiceNotFoundException: urn:jxta:uuid-F35E2A65415941F3B489BC29C886305905
         at net.jxta.impl.peergroup.GenericPeerGroup.lookupService(GenericPeerGroup.java:488)
         at net.jxta.impl.peergroup.RefCountPeerGroupInterface.lookupService(RefCountPeerGroupInterface.java:249)
         at net.jxta.impl.peergroup.RefCountPeerGroupInterface.lookupService(RefCountPeerGroupInterface.java:213)
         at src.ServiceTest.showGUI(ServiceTest.java:437)
         at src.ServiceTest.main(ServiceTest.java:316)
    Error starting JXTA platform: net.jxta.exception.ServiceNotFoundException: urn:jxta:uuid-F35E2A65415941F3B489BC29C886305905
    if you can test this application, can you tell me why i have this problem and how resolve it???
    This is very important for me.
    Thanks to all!!!!
    Miza

    and some problem in the music player with arabic font...
    http://img338.imageshack.us/img338/7371/screenshot0005lt7.jpg
    http://img261.imageshack.us/img261/5168/screenshot0004ee8.jpg

  • Problem with reading objects through ObjectInputStream

    HI
    Actually i have a problem of reading the objects from ObjectInputStream and getting StreamCorruptedException when i try to read as there is no limit to find the end of file i think iam getting the exception any suggestions please to overcome this problem..

    Of course I can, I have included two classes.
    MyMap that I shall store values in and then save to disk.
    Test Map that I stores one value in MyMap and then
    serialize to disk and the I do the reverse and se if my value is still there. Check out for yourself and please dont hestate to ask if you have trouble using it.
    import java.util.HashMap;
    import java.io.Serializable;
    * This class must implement Serializable to be stored in disk
    * with write(Object)
    public class MyMap implements Serializable
      private HashMap map = new HashMap();
      public void put(Serializable key, Serializable value)
        map.put(key,value);
      public Object get(Object key)
        return map.get(key);
    // Second class
    import java.io.*;
    public class TestMap
      public TestMap()
        try
          showHowToUseSerialize();
        catch(Throwable ignored)
          ignored.printStackTrace();
      private void showHowToUseSerialize()throws Throwable
        // First store anything to the class MyMap
        MyMap myMap = new MyMap();
        //  When yuo use put on it it only accept Serializable
        //  se how in the class
        myMap.put("key1","This is the first object in MyMap");
        // Then serialize it to disk.
        serialize(myMap);
        // Now you try to retreive from the file and see if you
        // can get the value key1 stored inside it.
        Object object = deserialize();
        // Cast it to the kind of object you have stored there.
        MyMap mapFromDisk = (MyMap)object;
        // See if key1 is really there.
        String value = (String)mapFromDisk.get("key1");
        // Print it out just be sure...
        System.out.println("key1 stored in MyMap in disk is: "+value);
      private Object deserialize()throws Throwable
        File f = new File("C:\\temp\\mymap.ser");
        if(!f.exists())
        { // Check that there really is such serialized file.
          throw new FileNotFoundException("Didnt find the serialized file: "+f);
        FileInputStream in = new FileInputStream(f);
        ObjectInputStream objIn = new ObjectInputStream(in);
        // Read in the object from the file.
        return objIn.readObject();
      private void serialize(Object myMap) throws Throwable
        File f = new File("C:\\temp\\mymap.ser");
        if(!f.exists())
          f.createNewFile();
        FileOutputStream out = new FileOutputStream(f);
        ObjectOutputStream objOut = new ObjectOutputStream(out);
        objOut.writeObject(myMap);
        objOut.close();
      public static void main(String[] args)
        new TestMap();
    }

  • Problem with fetching Map object from ObjectInputStream

    Hi, please can you help me with the following...I've never seen this before (with my limited experience of JDK1.5)
    ObjectInputStream is = new ObjectInputStream(new FileInputStream(store));
    Map<Integer, Report> readObject = (Map<Integer, Report>) is.readObject();This code gives me a warning...
    Type safety: The cast from Object to Map<Integer,Report> is actually checking against the erased type Map
    How can I get rid of this warning?

         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream( baos );
         List<String> list = new LinkedList<String>();
         list.add( "one" );
         list.add( "two" );
         oos.writeObject( list );
         oos.flush(); oos.close();
         ObjectInputStream ois = new ObjectInputStream
             ( new ByteArrayInputStream( baos.toByteArray() ) );
         List<String> list2 = (List<String>)ois.readObject();Give me 1 compile time error (Test.java:109: warning: [unchecked] unchecked cast), and no runtime errors.
    Removing the <String> from "list" add some more [uncheked], but still runs fine (no runtime warning). Adding a none-String only causes a problem when I try to "get" it. (class cast).
    When do you get this warning?

  • Problem to calling readObject(java.io.ObjectInputStream) using reflection

    Hi,
    I am facing the following problem
    I have an Employee class its overridden the following below methods
    private void readObject(java.io.ObjectInputStream inStream) {
         inStream.defaultReadObject();
    I am trying to call this method using reflection.
    my code is like this
         Class fis= Class.forName("java.io.FileInputStream");
         Constructor fcons = fis.getConstructor(new Class[]{String.class});
         Object fisObj = fcons.newInstance(new Object[]{"C:\\NewEmployee.ser"});
         Class ois= Class.forName("java.io.ObjectInputStream");     
         Constructor ocons = ois.getDeclaredConstructor(new Class[]{InputStream.class});
         Object oisObj = ocons.newInstance(new Object[] {fisObj});
         Method readObj = aClass.getDeclaredMethod("readObject", new Class[]{ois});
         readObj.setAccessible(true);
         Object mapObj = readObj.invoke(employeeObj,new Object[]{oisObj});
    The above code is call the readObject method, but it is failing while executing inStream.defaultReadObject() statement
    I am getting the following exception
    java.lang.reflect.InvocationTargetException
    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:585)
    at HackEmployee.reflect(HackEmployee.java:49)
    at HackEmployee.main(HackEmployee.java:131)
    Caused by: java.io.NotActiveException: not in call to readObject
    at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:474)
    at Employee.readObject(Employee.java:77)
    ... 6 more
    can anybody help me?
    ~ murali

    Hi,
    Here is the simple example.
    public class Employee implements Serializable {
    static final long serialVersionUID = 1L;
    static final int _VERSION = 2;
    private int eno;
    private String empName;
         private String paaword;
         private void readObject(java.io.ObjectInputStream inStream)
    throws IOException, ClassNotFoundException {
         int version = 0;
         BufferedInputStream bis = new BufferedInputStream(inStream);
         bis.mark(256);
         DataInputStream dis = new DataInputStream(bis);
         try {
              version = dis.readInt();
              Debug.println(Debug.INFO, _TAG, "Loading version=" + version);
         } catch(Exception e) {
              dis.reset();
         switch(version) {
              case 0:
              case 1:
                   inStream.defaultReadObject();
                   migrateDefaultEmployeeToEncryptionPassword();
                   break;
              case _VERSION:
                   inStream.defaultReadObject();
                   break;
              default:
                   throw new IOException("Unknown Version :" + version);
         private void writeObject(ObjectOutputStream aOutputStream)
    throws IOException {
         aOutputStream.writeInt(_VERSION);
         aOutputStream.defaultWriteObject();
    Now I am writing a tool that need to read data and print all the field and values in a file.
    So I am trying the same with reflecton by calling readObject(ObjectInputStream inStream).
    But here I am facing the problem, it is geving java.lang.reflect.InvocationTargetException while calling migrateDefaultEmployeeToEncryptionPassword(.
    Hope you got my exact scenerio.
    Thanks for your replay
    ~ Murali

  • Socket ObjectOutputStream or ObjectInputStream problem?

    Hi all!
    I have a problem with sockets and ObjectInputStreams objects: The first time I write into the ObjectOutputStream, the other side (ObjectInputStream) receives the object, the second time the ObjectInputStream doesnt receive it and the third time I've got an exception in the ObjectOutputStream -->
    java.net.SocketException: Software caused connection abort: socket write error
    at java.net.SocketOutputStream.socketWrite0(Native Method)
    The objects Im working with are mouse events and here is my code :
    // using a Thread to send packets from a queue 
        public void run(){
             Package pck;
             while(connected){
                 pck = queue.pop();
                 if (pck!=null){
                     sendpck(pck, socketList);
    public void sendpck(Package pck , LinkedList<Socket> list){
            ObjectOutputStream oos = null;
            for(Socket sock: list){
                try {
                    oos = new ObjectOutputStream(sock.getOutputStream()); // 1st time sends, 2nd seems to send, 3rd Exception
                    oos.writeObject(pck);
                    oos.flush();
                } catch (IOException ex) {
                    ex.printStackTrace();
        }The other side code for listening:
    public void prepareListener(Socket socketClient){
            try {
                ois = new ObjectInputStream(socketClient.getInputStream());
            } catch (IOException e) {
                connected = false;
        public void run() {
            while(connected){
                try {
                    Package pack = (Package)ois.readObject();  // recieves only once,
                        // execute Mouse event
                } catch (IOException e) {
                    this.connected=false;
                } catch (ClassNotFoundException e) {
                    this.connected=false;
        }I have doubts because the prepareListener method is called from an static method and I dont know if that could be a problem:
        public static void connectService(Socket clientSocket){
            ClientThread listenerClient = new ClientThread();
            listenerClient.prepareListener(clientSocket);
            if (listenerClient.isConnected()){
                Thread myThread = new Thread(listenerClient);
                myThread.start();
        }I hope I was clear..... please I need your help....
    Thanks in advance
    Edited by: Pogasu on May 10, 2009 8:13 PM

    Thanks for answering!
    You were right, i was ignoring an exception on the client side: java.io.StreamCorruptedException: invalid type code: AC.
    I create one ObjectOutputStream for each socket from my socketlist each time i want to send and for listening doesnt the thread starts with an InputStream. As I Understand, my problem is that the InputStream has a connection only with one OutputStream and the next time i want to write something I create another OutputStream that isnt the original one. Am I right? What I should have is a list of created OutputStreams instead of sockets?

  • ObjectInputStream - ObjectOutputStream, socket problem

    Hello,
    I'm tring to send and receive some object between a client and a server application.
    When the client application send an object the server is stock.
    This is a part of the server code:
    try
    inObj = new ObjectInputStream(client.getInputStream()); /// here the server program is stock
         mes1 = (Message) inObj.readObject();
         System.out.println(mes1);
         out.println("end");
    catch (ClassNotFoundException e)
    e.printStackTrace();
    catch(IOException e)
         e.printStackTrace();
    The client code:
    try
         in=new BufferedReader(new InputStreamReader(soclu.getInputStream()));
         out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(soclu.getOutputStream())),true);
         outObj = new ObjectOutputStream(soclu.getOutputStream());
         out.print("Info");
         //          out.flush();
         outObj.writeObject(m1);
         outObj.flush();
         raspuns = in.readLine();
         System.out.println(raspuns);
         System.out.println("Closing the communication!");
         out.print("end");
         out.close();
         in.close();
         outObj.close();
         soclu.close();
    catch(IOException e)
         System.out.println("Problems Tx/Rx");
         e.printStackTrace();
    The class Message implements Serializable
    if there is somebody hwo cold help me I appreciate that.
    Thnak you,
    aclaudia1

    You should not be opening both a PrintWriter and an ObjectOutputStream on the same socket. You should use a single stream to do all the output on the socket.

  • JXTA HelloWorld problem

    Hi!
    I've been proggraming in Java quite a while now, but I need to use JXTA in a project and I'm totally new to it. I'm trying to run some examples in JBuilder7 (the classic HelloWorld among others), and I keep getting the following exception (it looks huge):
    Netscape security model is no longer supported.
    Please migrate to the Java 2 security model instead.
    java.lang.NoSuchMethodError
    at xjava.security.IJCE_SecuritySupport.registerTargets(IJCE_SecuritySupport.java:155)
    at xjava.security.IJCE_SecuritySupport.<clinit>(IJCE_SecuritySupport.java:134)
    at xjava.security.IJCE.findTarget(IJCE.java:498)
    at xjava.security.IJCE.getProvidersInternal(IJCE.java:638)
    at xjava.security.IJCE.getClassCandidate(IJCE.java:426)
    at xjava.security.IJCE.getImplementationClass(IJCE.java:410)
    at xjava.security.IJCE.getImplementation(IJCE.java:367)
    at xjava.security.Cipher.getInstance(Cipher.java:485)
    at xjava.security.Cipher.getInstance(Cipher.java:452)
    at xjava.security.Cipher.getInstance(Cipher.java:395)
    at COM.claymoresystems.crypto.PEMData.writePEMObject(PEMData.java:154)
    at COM.claymoresystems.crypto.EAYEncryptedPrivateKey.writePrivateKey(EAYEncryptedPrivateKey.java:109)
    at net.jxta.impl.endpoint.tls.PeerCerts.appendPrivateKey(PeerCerts.java:174)
    at net.jxta.impl.endpoint.tls.PeerCerts.genPeerRootCert(PeerCerts.java:137)
    at net.jxta.impl.endpoint.tls.PeerCerts.generateCerts(PeerCerts.java:457)
    at net.jxta.impl.endpoint.tls.TlsConfig.init(TlsConfig.java:185)
    at net.jxta.impl.peergroup.Configurator.configureTls(Configurator.java:265)
    at net.jxta.impl.peergroup.Configurator.<init>(Configurator.java:202)
    at net.jxta.impl.peergroup.Platform.init(Platform.java:252)
    at net.jxta.peergroup.PeerGroupFactory.newPlatform(PeerGroupFactory.java:210)
    at net.jxta.peergroup.PeerGroupFactory.newNetPeerGroup(PeerGroupFactory.java:284)
    at SimpleJxtaApp.startJxta(SimpleJxtaApp.java:91)
    at SimpleJxtaApp.main(SimpleJxtaApp.java:73)
    Unexpected exception in IJCE_SecuritySupport.registerTargets()
    Please report this as a bug to <[email protected]>, including
    any other messages displayed on the console, and a description of what
    appeared to cause the error.
    java.lang.InternalError: Unexpected exception in IJCE_SecuritySupport.registerTargets()
    at xjava.security.IJCE.reportBug(IJCE.java:701)
    at xjava.security.IJCE_SecuritySupport.<clinit>(IJCE_SecuritySupport.java:138)
    at xjava.security.IJCE.findTarget(IJCE.java:498)
    at xjava.security.IJCE.getProvidersInternal(IJCE.java:638)
    at xjava.security.IJCE.getClassCandidate(IJCE.java:426)
    at xjava.security.IJCE.getImplementationClass(IJCE.java:410)
    at xjava.security.IJCE.getImplementation(IJCE.java:367)
    at xjava.security.Cipher.getInstance(Cipher.java:485)
    at xjava.security.Cipher.getInstance(Cipher.java:452)
    at xjava.security.Cipher.getInstance(Cipher.java:395)
    at COM.claymoresystems.crypto.PEMData.writePEMObject(PEMData.java:154)
    at COM.claymoresystems.crypto.EAYEncryptedPrivateKey.writePrivateKey(EAYEncryptedPrivateKey.java:109)
    at net.jxta.impl.endpoint.tls.PeerCerts.appendPrivateKey(PeerCerts.java:174)
    at net.jxta.impl.endpoint.tls.PeerCerts.genPeerRootCert(PeerCerts.java:137)
    at net.jxta.impl.endpoint.tls.PeerCerts.generateCerts(PeerCerts.java:457)
    at net.jxta.impl.endpoint.tls.TlsConfig.init(TlsConfig.java:185)
    at net.jxta.impl.peergroup.Configurator.configureTls(Configurator.java:265)
    at net.jxta.impl.peergroup.Configurator.<init>(Configurator.java:202)
    at net.jxta.impl.peergroup.Platform.init(Platform.java:252)
    at net.jxta.peergroup.PeerGroupFactory.newPlatform(PeerGroupFactory.java:210)
    at net.jxta.peergroup.PeerGroupFactory.newNetPeerGroup(PeerGroupFactory.java:284)
    at SimpleJxtaApp.startJxta(SimpleJxtaApp.java:91)
    at SimpleJxtaApp.main(SimpleJxtaApp.java:73)
    I have installed everything by the book, and added the libraries and evrything, but I can't get further. I tried to report the bug as the message says, but the e-mail address doesn't exist (must be some old stuff I guess). Anybody has a clue about this?
    Thanks in advance,
    Marta

    I know nothing about this other than what I found in a couple of Google searches:
    http://www.google.com/search?num=100&hl=en&lr=lang_en&ie=ISO-8859-1&q=%22Netscape+security+model%22+%22+Please+migrate+to+the+Java+2+security+model%22&btnG=Google+Search
    http://www.google.com/search?q=xjava.security
    Which I suggest you review. It appears that something you have is trying to reference an old security feature that used to be in Netscape. It no longer is valid, so the message. Your guess re the age of the product is probably right. The xjava.security package is a part of a third-party security product from Cryptix.
    Good hunting!

  • Problem in loading Objects using ObjectInputStream

    Hello,
    This method load data from the secondary memory/
    public void load() throws Exception
    //File dataFile = new File(".\\center.dat");
    //if (dataFile.exists())
    ObjectInputStream in = null;
    in = new ObjectInputStream(new
    FileInputStream("center.dat"));
    System.out.println("Open file for reading");
    if(in == null)
    System.out.println("File does not open correctly");
    //Load courses
    courses = (CourseList)in.readObject();
    System.out.println("Successfully read courses of the system");
    //Load Modules
    modules = (ModuleList)in.readObject();
    System.out.println("Successfully read modules of the system");
    //Load Batches
    batches = (BatchList)in.readObject();
    System.out.println("Successfully read batches of the system");
    //Load Candidates
    candidates = (CandidateList)in.readObject();
    System.out.println("Successfully read candidates of the system");
    in.close();
    System.out.println("Close objects file");
    As i print the message of the exception it print Code excepting
    I get this exception when i call readObject method and i had checked Object of ObjectInputStream i.e. in is not null.
    Please help me

    1) Stick to your thread: http://forum.java.sun.com/thread.jspa?threadID=651247
    2) What's the stack trace?

Maybe you are looking for

  • Terrible Packet Loss in Game- Please help!

    Computing statistics for 100 seconds... Source to Here This Node/Link Hop RTT Lost/Sent = Pct Lost/Sent = Pct Address 0 Sam-PC.home [192.168.1.5] 0/ 25 = 0% | 1 2ms 0/ 25 = 0% 0/ 25 = 0% Wireless_Broadband_Router.home [192.168.1.1] 1/ 25 = 4% | 2 13m

  • IPHONE 3GS TO IO6

    Well I updated to io6 and I have no wi-fi, no 3gs, hardly any phone reception.. Ive read loads but most people seem to have an iphone 4. Ive tried everything, a complete erase all etc and even a backup in case it reinstalled ios5 but no joy can anyon

  • How to make Microsoft.VSTS.TCM.Steps reportable ?

    Hi, I am creating a report using report builder and I need to drill down report of test execution. I would need Steps counts of test case. For that I need to mark Microsoft.VSTS.TCM.Steps reportable. But when we try to upload that to server, we get e

  • Does "reset and erase all content" update iOS?

    Hi guys, My girlfriend has an iPhone 4 that has been giving her a lot of problems lately. I want to restore it but I don't want to update it to iOS 6 just yet. Instead of restoring through iTunes, if I restore via settings>general>"reset settings and

  • Varient Creatin

    Hello, Please tell me how to create a varient ( to lock the T-Codes ) while schduling background jobs. Gayatry.