Java程序,用于从位于服务器中的.ser文件中读取对象

时间:2013-03-23 18:31:32

标签: java file http object

我的想法是我想从位于服务器中的序列化文件中读取对象。怎么做?

我只能使用以下代码读取.txt文件:

   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!!!");
    }
   }

1 个答案:

答案 0 :(得分:0)

您可以使用此方法执行此操作

  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);
    }
  }

将其与urlConn.getInputStream()一起提供,您将获得ObjectDataInputStream不适合阅读使用ObjectOutputStream完成的序列化objets。分别使用ObjectInputStream

要将对象写入文件,还有另一种方法

  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);
    }
  }