簡體   English   中英

Java程序從服務器中的.ser文件讀取對象

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

我的想法是我想從服務器中的序列化文件中讀取對象。 怎么做?

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM