Exemplo n.º 1
0
 public static void main(String args[]) throws Exception {
   File f = new File("tmp.ser");
   if (args[0].compareTo("-s") == 0) {
     FileOutputStream of = new FileOutputStream(f);
     ObjectOutputStream oos = new ObjectOutputStream(of);
     Class cl = Class.forName(args[1]);
     oos.writeObject(cl);
     if (ObjectStreamClass.lookup(cl) != null) oos.writeObject(cl.newInstance());
     oos.close();
     System.out.println("Serialized Class " + cl.getName());
   } else if (args[0].compareTo("-de") == 0) {
     FileInputStream inf = new FileInputStream(f);
     ObjectInputStream ois = new ObjectInputStream(inf);
     Class cl = null;
     try {
       cl = (Class) ois.readObject();
       throw new Error("Expected InvalidClassException to be thrown");
     } catch (InvalidClassException e) {
       System.out.println("Caught expected exception DeSerializing class " + e.getMessage());
     }
     ois.close();
   } else if (args[0].compareTo("-doe") == 0) {
     FileInputStream inf = new FileInputStream(f);
     ObjectInputStream ois = new ObjectInputStream(inf);
     Class cl = null;
     cl = (Class) ois.readObject();
     try {
       ois.readObject();
       throw new Error("Expected InvalidClassException to be thrown");
     } catch (InvalidClassException e) {
       System.out.println("Caught expected exception DeSerializing class " + e.getMessage());
     }
     ois.close();
   } else if (args[0].compareTo("-d") == 0) {
     FileInputStream inf = new FileInputStream(f);
     ObjectInputStream ois = new ObjectInputStream(inf);
     Class cl = (Class) ois.readObject();
     try {
       ois.readObject();
     } catch (EOFException e) {
     }
     ois.close();
     System.out.println("DeSerialized Class " + cl.getName());
   }
 }
Exemplo n.º 2
0
  /**
   * Deserialize the contents of File with given name containing a string and return the resulting
   * string. If the indicated file doesnt exist or an error occurs, null is returned. If casually is
   * false, an error message is printed and an exception is raised if the file was not found or an
   * error occured on loading.
   */
  public static Object loadObject(String Filename, boolean casually) {
    Object s = null;

    File f = new File(Filename);
    if (f.exists()) {
      try {
        s = (Object) load(new File(Filename));
      } catch (InvalidClassException e) {
        System.err.println(
            "WARNING: loading object File "
                + Filename
                + " not possible, this may happen on source code changes.");
        System.err.println(e.getMessage());
      } catch (Exception e) {
        throw new RuntimeException(
            "WARNING: loading object File " + Filename + " not possible! (" + e.getMessage() + ")");
      }
      return s;
    } else {
      if (!casually) System.err.println("Error in Serializer: file " + Filename + " not found!");
      return null;
    }
  }