Search code examples
javafilehttpobject

Java program to read objects from a .ser file located in a server


My idea is that I want to read an object from a serialized file located in a server. How to do that?

I can only read .txt file using the following code :

   void getInfo() {
    try {
        URL url;
        URLConnection urlConn;
        DataInputStream dis;

        url = new URL("http://localhost/Test.txt");

        // Note:  a more portable URL: 
        //url = new URL(getCodeBase().toString() + "/ToDoList/ToDoList.txt");

        urlConn = url.openConnection();
        urlConn.setDoInput(true);
        urlConn.setUseCaches(false);

        dis = new DataInputStream(urlConn.getInputStream());

        String s;
        while ((s = dis.readLine()) != null) {
            System.out.println(s);
        }
        dis.close();
    } catch (MalformedURLException mue) {
        System.out.println("Error!!!");
    } catch (IOException ioe) {
        System.out.println("Error!!!");
    }
   }

Solution

  • You can do this with this method

      public Object deserialize(InputStream is) {
        ObjectInputStream in;
        Object obj;
        try {
          in = new ObjectInputStream(is);
          obj = in.readObject();
          in.close();
          return obj;
        }
        catch (IOException ex) {
          ex.printStackTrace();
          throw new RuntimeException(ex);
        }
        catch (ClassNotFoundException ex) {
          ex.printStackTrace();
          throw new RuntimeException(ex);
        }
      }
    

    feed it with urlConn.getInputStream() and you'll get the Object. DataInputStream is not fit to read serialized objets that are done with ObjectOutputStream. Use ObjectInputStream respectively.

    To write an object to the file there's another method

      public void serialize(Object obj, String fileName) {
        FileOutputStream fos;
        ObjectOutputStream out;
        try {
          fos = new FileOutputStream(fileName);
          out = new ObjectOutputStream(fos);
          out.writeObject(obj);
          out.close();
        }
        catch (IOException ex) {
          ex.printStackTrace();
          throw new RuntimeException(ex);
        }
      }