2

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

我只能使用以下代码读取 .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!!!");
    }
   }
4

1 回答 1

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()你会得到Object. DataInputStream不适合读取用ObjectOutputStream. 分别使用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);
    }
  }
于 2013-03-23T18:43:14.367 回答