Example usage for java.io ObjectInputStream ObjectInputStream

List of usage examples for java.io ObjectInputStream ObjectInputStream

Introduction

In this page you can find the example usage for java.io ObjectInputStream ObjectInputStream.

Prototype

public ObjectInputStream(InputStream in) throws IOException 

Source Link

Document

Creates an ObjectInputStream that reads from the specified InputStream.

Usage

From source file:lirmm.inria.fr.math.TestUtils.java

/**
 * Serializes an object to a bytes array and then recovers the object from the bytes array.
 * Returns the deserialized object.// w  w w .  j  av a2  s  .c o  m
 *
 * @param o  object to serialize and recover
 * @return  the recovered, deserialized object
 */
public static Object serializeAndRecover(Object o) {
    try {
        // serialize the Object
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream so = new ObjectOutputStream(bos);
        so.writeObject(o);

        // deserialize the Object
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream si = new ObjectInputStream(bis);
        return si.readObject();
    } catch (IOException ioe) {
        return null;
    } catch (ClassNotFoundException cnfe) {
        return null;
    }
}

From source file:cpd3314.buildit12.CPD3314BuildIt12.java

/**
 * Build a sample method that saves a handful of car instances as Serialized
 * objects, and as JSON objects, then re-open the saved versions in a
 * different method//from ww w. j av  a2  s .  c o  m
 */
public static void doBuildIt2Input() {
    // Unserialize the Objects -- Save them to an ArrayList and Output
    try {
        FileInputStream objFile = new FileInputStream("cars.obj");
        ObjectInputStream objStream = new ObjectInputStream(objFile);

        ArrayList<Car> cars = new ArrayList<>();

        boolean eof = false;
        while (!eof) {
            try {
                cars.add((Car) objStream.readObject());
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(CPD3314BuildIt12.class.getName()).log(Level.SEVERE, null, ex);
            } catch (EOFException ex) {
                // We must catch the EOF exception to leave the loop
                eof = true;
            }
        }

        System.out.println("Unserialized Data:");
        for (Car car : cars) {
            System.out.printf("Make: %s, Model: %s, Year: %d\n", car.getMake(), car.getModel(), car.getYear());
        }
    } catch (IOException ex) {
        Logger.getLogger(CPD3314BuildIt12.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Read from JSON and Output
    try {
        File file = new File("cars.json");
        Scanner input = new Scanner(file);
        while (input.hasNext()) {
            JSONParser parse = new JSONParser();
            try {
                // This should be the root JSON Object, which has an array of Car objects
                JSONObject json = (JSONObject) parse.parse(input.nextLine());

                // We pull the array out to work with it
                JSONArray cars = (JSONArray) json.get("cars");

                System.out.println("Un-JSON-ed Data:");
                for (Object car : cars) {
                    // Convert each Object to a JSONObject
                    JSONObject carJSON = (JSONObject) car;
                    // Convert each JSONObject to an actual Car
                    Car carObj = new Car(carJSON);
                    // Output from the Actual Car class                        
                    System.out.printf("Make: %s, Model: %s, Year: %d\n", carObj.getMake(), carObj.getModel(),
                            carObj.getYear());
                }
            } catch (ParseException ex) {
                Logger.getLogger(CPD3314BuildIt12.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(CPD3314BuildIt12.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.ambraproject.model.article.ArticleTypeTest.java

@Test
public void testDeserializedArticleTypeEquality() throws Exception {
    ArticleType art1 = ArticleType/*from   w w w . ja v a 2 s  .  c  o m*/
            .getArticleTypeForURI(new URI("http://rdf.plos.org/RDF/articleType/Interview"), false);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bout);

    out.writeObject(art1);
    out.flush();

    ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
    ObjectInputStream in = new ObjectInputStream(bin);

    ArticleType art2 = (ArticleType) in.readObject();

    assertTrue(art1 == art2, "Article 1 == Article 2");
    assertTrue(art1.equals(art2), "Article 1 should .equals() Article 2");
}

From source file:com.sec.ose.osi.ui.cache.UICache.java

@SuppressWarnings("unchecked")
private void load() {
    File file = new File(CACHE_FILE_NAME);
    if (file.exists() == false) {
        return;//w  w  w.j a va  2 s . com
    }

    log.debug("load cache from cache file");

    ObjectInputStream ois = null;
    try {
        ois = new ObjectInputStream(new FileInputStream(file)); // IO, FileNotFound

        this.mMap = (HashMap<Integer, UIEntity>) ois.readObject(); // ClassNotFound

    } catch (FileNotFoundException e) {
        log.warn(e);
    } catch (IOException e) {
        log.warn(e);
        file.delete();
    } catch (ClassNotFoundException e) {
        log.warn(e);
        file.delete();
    } catch (Exception e) {
        log.warn(e);
        file.delete();
    } finally {

        if (ois != null) {
            try {
                ois.close();
            } catch (IOException e) {
                log.warn(e);
            }
        }
        ois = null;
    }
}

From source file:com.mtgi.io.RelocatableFileTest.java

@Test
public void testRelocate() throws IOException, ClassNotFoundException {
    FileUtils.writeStringToFile(source, "here is some data");

    output.writeObject(inst);//from w  w w. j a v  a  2  s . c  o m
    output.close();

    assertTrue("original file still here", inst.getLocalFile().isFile());
    assertEquals("source file is unchanged", "here is some data",
            FileUtils.readFileToString(inst.getLocalFile()));

    RelocatableFile transferred = (RelocatableFile) new ObjectInputStream(
            new ByteArrayInputStream(buffer.toByteArray())).readObject();
    assertNotNull("file loaded", transferred);
    assertNotNull("local file defined", transferred.getLocalFile());
    assertTrue("local file exists", transferred.getLocalFile().isFile());
    assertFalse("reloaded file points to a new path",
            inst.getLocalFile().getCanonicalPath().equals(transferred.getLocalFile().getCanonicalPath()));

    assertEquals("transferred file contains source data", "here is some data",
            FileUtils.readFileToString(transferred.getLocalFile()));
    assertTrue("transferred file is closed", transferred.getLocalFile().delete());
}

From source file:io.github.azige.whitespace.Cli.java

static void execute(InputStream input, String path) throws IOException, ClassNotFoundException {
    WhitespaceVM vm = new DefaultWhitespaceVM();
    Program program;//from   w  w  w  .j a va 2s  .  c om
    if (path.endsWith(WHITESPACE_BINARY_FILE_SUFFIX)) {
        ObjectInputStream oinput = new ObjectInputStream(new GZIPInputStream(input));
        program = (Program) oinput.readObject();
    } else {
        Interpreter interpreter = createInterpreter();
        program = interpreter.interpret(createReader(input));
    }
    vm.getProcessor().loadProgram(program);
    vm.getProcessor().executeAll(true);
}

From source file:jedi.util.serialization.Pickle.java

/**
 * Receives a sequence of bytes and returns a object.
 * //ww  w.  ja v  a 2  s  .c o m
 * @param s Sequence of bytes.
 * @return Object
 */
public static Object loads(String s) {
    Object o = null;
    ByteArrayInputStream bais;

    try {
        bais = new ByteArrayInputStream(Base64.decodeBase64(s.getBytes()));
        ObjectInputStream ois = new ObjectInputStream(bais);

        o = ois.readObject();

        ois.close();
        bais.close();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return o;
}

From source file:ByteFIFOTest.java

private void dst() {
    try {//from  w  ww.  j a v a2 s .co m
        boolean justAddOne = true;
        int count = 0;
        byte[] dstData = new byte[srcData.length];

        while (count < dstData.length) {
            if (!justAddOne) {
                byte[] buf = fifo.removeAll();
                if (buf.length > 0) {
                    System.arraycopy(buf, 0, dstData, count, buf.length);
                    count += buf.length;
                }

                System.out.println("just removed " + buf.length + " bytes");
            } else {
                byte b = fifo.remove();
                dstData[count] = b;
                count++;

                System.out.println("just removed exactly 1 byte");
            }

            justAddOne = !justAddOne;
        }

        System.out.println("received all data, count=" + count);

        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(dstData));

        String[] line = (String[]) ois.readObject();

        for (int i = 0; i < line.length; i++) {
            System.out.println("line[" + i + "]=" + line[i]);
        }
    } catch (ClassNotFoundException x1) {
        x1.printStackTrace();
    } catch (IOException iox) {
        iox.printStackTrace();
    } catch (InterruptedException x) {
        x.printStackTrace();
    }
}

From source file:com.bskyb.cg.environments.hash.PersistentHash.java

private synchronized void refreshFromStore(String dirname) throws IOException {

    FileInputStream fis;//from  ww  w  .  ja v a  2  s.  c  o  m
    BufferedInputStream bis;
    Serializable messageEntry;
    ObjectInputStream ois;
    File emptyDir = new File(dirname);
    FilenameFilter onlyDat = new FileExtFilter(STOREFILEEXT);
    File[] files = emptyDir.listFiles(onlyDat);

    hash.clear();

    for (File file : files) {
        fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis);
        ois = new ObjectInputStream(bis);
        try {
            messageEntry = (Serializable) ois.readObject();
        } catch (ClassNotFoundException e) {
            throw new IOException(e.toString());
        } catch (ClassCastException e) {
            throw new IOException(e.toString());
        } catch (StreamCorruptedException e) {
            throw new IOException(e.toString());
        }
        try {
            hash.put(file.getName(), (Message) messageEntry);
        } catch (ClassCastException e) {
            throw new IOException(e.toString());
        }
        fis.close();
    }
}

From source file:com.sun.j2ee.blueprints.waf.controller.web.flow.handlers.ClientStateFlowHandler.java

public String processFlow(HttpServletRequest request) throws FlowHandlerException {

    String forwardScreen = request.getParameter("referring_screen");
    // de-serialize the request attributes.
    Map params = (Map) request.getParameterMap();
    HashMap newParams = new HashMap();
    String cacheId = request.getParameter("cacheId");
    if (!params.isEmpty()) {
        Iterator it = params.keySet().iterator();
        // put the request attributes stored in the session in the request
        while (it.hasNext()) {
            String key = (String) it.next();
            if (key.startsWith(cacheId + "_attribute_")) {
                String[] values = (String[]) params.get(key);
                String valueString = values[0];
                byte[] bytes = Base64.decode(valueString.getBytes());
                try {
                    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
                    Object requestObject = requestObject = ois.readObject();
                    ois.close();// w  w w .j a v  a 2s. com
                    // put the de-serialized object back into the request
                    String requestObjectKey = key.substring((cacheId + "_attribute_").length(), key.length());
                    request.setAttribute(requestObjectKey, requestObject);
                } catch (java.io.OptionalDataException ode) {
                    System.err.println("ClientCacheLinkFlowHandler caught: " + ode);
                } catch (java.lang.ClassNotFoundException cnfe) {
                    System.err.println("ClientCacheLinkFlowHandler caught: " + cnfe);
                } catch (java.io.IOException iox) {
                    System.err.println("ClientCacheLinkFlowHandler caught: " + iox);
                }
            }
        }
    }
    return forwardScreen;
}