Example usage for java.io ObjectOutputStream ObjectOutputStream

List of usage examples for java.io ObjectOutputStream ObjectOutputStream

Introduction

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

Prototype

public ObjectOutputStream(OutputStream out) throws IOException 

Source Link

Document

Creates an ObjectOutputStream that writes to the specified OutputStream.

Usage

From source file:CardWriter.java

public static void main(String[] args) {
    Card3 card = new Card3(12, Card3.SPADES);
    System.out.println("Card to write is: " + card);

    try {//from ww w  .  j  a v a2 s . co  m
        FileOutputStream out = new FileOutputStream("card.out");
        ObjectOutputStream oos = new ObjectOutputStream(out);
        oos.writeObject(card);
        oos.flush();
    } catch (Exception e) {
        System.out.println("Problem serializing: " + e);
    }
}

From source file:DataIOTest2.java

public static void main(String[] args) throws IOException {

    // write the data out
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("invoice1.txt"));

    double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
    int[] units = { 12, 8, 13, 29, 50 };
    String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" };

    for (int i = 0; i < prices.length; i++) {
        out.writeDouble(prices[i]);//from   w w  w . j a  v a  2 s . co m
        out.writeChar('\t');
        out.writeInt(units[i]);
        out.writeChar('\t');
        out.writeChars(descs[i]);
        out.writeChar('\n');
    }
    out.close();

    // read it in again
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("invoice1.txt"));

    double price;
    int unit;
    String desc;
    double total = 0.0;

    try {
        while (true) {
            price = in.readDouble();
            in.readChar(); // throws out the tab
            unit = in.readInt();
            in.readChar(); // throws out the tab
            desc = in.readLine();
            System.out.println("You've ordered " + unit + " units of " + desc + " at $" + price);
            total = total + unit * price;
        }
    } catch (EOFException e) {
    }
    System.out.println("For a TOTAL of: $" + total);
    in.close();
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.clustering.ClusterCentroidsMain.java

public static void main(String[] args) throws Exception {
    //        String clutoVectors = args[0];
    //        String clutoOuputClusters = args[1];
    //        String outputClusterCentroids = args[2];

    File[] files = new File("//home/user-ukp/data2/debates-ranked.100-xmi").listFiles(new FilenameFilter() {
        @Override/*  w w  w.  j a  v  a2s .  c  o  m*/
        public boolean accept(File dir, String name) {
            //                        return name.startsWith("arg") && name.endsWith(".mat");
            return name.startsWith("sent") && name.endsWith(".mat");
        }
    });
    for (File matFile : files) {
        String clutoVectors = matFile.getAbsolutePath();
        //            String clutoOuputClusters = matFile.getAbsolutePath() + ".clustering.100";
        String clutoOuputClusters = matFile.getAbsolutePath() + ".clustering.1000";
        String outputClusterCentroids = matFile.getAbsolutePath() + ".bin";

        TreeMap<Integer, Vector> centroids = computeClusterCentroids(clutoVectors, clutoOuputClusters);

        // and serialize
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                new FileOutputStream(outputClusterCentroids));
        objectOutputStream.writeObject(centroids);
        IOUtils.closeQuietly(objectOutputStream);
    }

    //        System.out.println(centroids);
    //        embeddingsToDistance(args[0], centroids, args[2]);
}

From source file:com.puffywhiteshare.PWSApp.java

/**
 * @param args/*www.  ja va 2 s.  co m*/
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    CloudBucket cloud = new CloudBucket();
    logger.info("Test my output bitches");
    Yaml y = new Yaml();
    File f = new File("Playing.yml");
    FileInputStream fis = new FileInputStream(f);
    Map m = (Map) y.load(fis);

    Long startFiles = System.currentTimeMillis();
    Iterator<File> fileIterator = FileUtils.iterateFiles(new File("/Users/chad/Pictures/."), null, true);
    do {
        File file = fileIterator.next();
        cloud.add(file);
    } while (fileIterator.hasNext());
    Long endFiles = System.currentTimeMillis();
    System.out.println("Files processing took " + ((endFiles - startFiles)));

    Long startSer = System.currentTimeMillis();
    String filename = "cloud.ser";
    FileOutputStream fos = null;
    ObjectOutputStream out = null;
    try {
        fos = new FileOutputStream(filename);
        out = new ObjectOutputStream(fos);
        out.writeObject(cloud);
        out.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    Long endSer = System.currentTimeMillis();
    System.out.println("Files processing took " + ((endSer - startSer)));

    logger.info(" Size = " + FileUtils.byteCountToDisplaySize(cloud.getSize()));
    logger.info("Count = " + cloud.getCount());

    /*
    Set<String> buckets = m.keySet();
    System.out.println(m.toString());
    for(String bucket : buckets) {
       logger.info("Bucket = " + bucket);
       logger.info("Folders = " + m.get(bucket));
       List<Object> folders = (List<Object>) m.get(bucket);
       for(Object folder : folders) {
    if(folder instanceof String) {
       logger.info("Folder Root = " + folder);
    } else if(folder instanceof Map) {
       logger.info("Folder Map = " + folder);
    }
       }
       BlockingQueue<File> fileFeed = new ArrayBlockingQueue<File>(10);
               
       Map folderMap = (Map) m.get(bucket);
       Set<String> folders = folderMap.entrySet();
       for(String folder : folders) {
    logger.info("Folder = " + folder);
       }
               
    }
    */
}

From source file:CardReader.java

public static void main(String[] args) {
    Card3 card = new Card3(12, Card3.SPADES);
    System.out.println("Card to write is: " + card);

    try {//from  w w  w  .  jav a2s.com
        FileOutputStream out = new FileOutputStream("card.out");
        ObjectOutputStream oos = new ObjectOutputStream(out);
        oos.writeObject(card);
        oos.flush();
    } catch (Exception e) {
        System.out.println("Problem serializing: " + e);
    }

    Card3 acard = null;

    try {
        FileInputStream in = new FileInputStream("card.out");
        ObjectInputStream ois = new ObjectInputStream(in);
        acard = (Card3) (ois.readObject());
    } catch (Exception e) {
        System.out.println("Problem serializing: " + e);
    }

    System.out.println("Card read is: " + acard);

}

From source file:com.textocat.textokit.morph.opencorpora.resource.XmlDictionaryParserLauncher.java

public static void main(String[] args) throws Exception {
    XmlDictionaryParserLauncher cfg = new XmlDictionaryParserLauncher();
    new JCommander(cfg, args);

    MorphDictionaryImpl dict = new MorphDictionaryImpl();
    DictionaryExtension ext = cfg.dictExtensionClass.newInstance();
    FileInputStream fis = FileUtils.openInputStream(cfg.dictXmlFile);
    try {/*from w ww. ja v a2s . co m*/
        new XmlDictionaryParser(dict, ext, fis).run();
    } finally {
        IOUtils.closeQuietly(fis);
    }

    log.info("Preparing to serialization...");
    long timeBefore = currentTimeMillis();
    OutputStream fout = new BufferedOutputStream(FileUtils.openOutputStream(cfg.outputFile), 8192 * 8);
    ObjectOutputStream out = new ObjectOutputStream(fout);
    try {
        out.writeObject(dict.getGramModel());
        out.writeObject(dict);
    } finally {
        out.close();
    }
    log.info("Serialization finished in {} ms.\nOutput size: {} bytes", currentTimeMillis() - timeBefore,
            cfg.outputFile.length());
}

From source file:Shape.java

public static void main(String[] args) throws Exception {
    List shapeTypes, shapes;//from  ww w.  j a  v  a 2  s  . c o m
    if (args.length == 0) {
        shapeTypes = new ArrayList();
        shapes = new ArrayList();

        shapeTypes.add(Circle.class);
        shapeTypes.add(Square.class);
        shapeTypes.add(Line.class);

        shapes.add(new Square(4, 3, 200));
        shapes.add(new Circle(1, 2, 100));
        shapes.add(new Line(1, 2, 100));

        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("CADState.out"));
        out.writeObject(shapeTypes);
        Line.serializeStaticState(out);
        out.writeObject(shapes);
    } else {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(args[0]));
        shapeTypes = (List) in.readObject();
        Line.deserializeStaticState(in);
        shapes = (List) in.readObject();
    }

    System.out.println(shapes);
}

From source file:ObjectStreams.java

public static void main(String[] args) throws IOException, ClassNotFoundException {

    ObjectOutputStream out = null;
    try {/*from w w  w .j av a  2  s  . c  o m*/
        out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));

        out.writeObject(Calendar.getInstance());
        for (int i = 0; i < prices.length; i++) {
            out.writeObject(prices[i]);
            out.writeInt(units[i]);
            out.writeUTF(descs[i]);
        }
    } finally {
        out.close();
    }

    ObjectInputStream in = null;
    try {
        in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(dataFile)));

        Calendar date = null;
        BigDecimal price;
        int unit;
        String desc;
        BigDecimal total = new BigDecimal(0);

        date = (Calendar) in.readObject();

        System.out.format("On %tA, %<tB %<te, %<tY:%n", date);

        try {
            while (true) {
                price = (BigDecimal) in.readObject();
                unit = in.readInt();
                desc = in.readUTF();
                System.out.format("You ordered %d units of %s at $%.2f%n", unit, desc, price);
                total = total.add(price.multiply(new BigDecimal(unit)));
            }
        } catch (EOFException e) {
        }
        System.out.format("For a TOTAL of: $%.2f%n", total);
    } finally {
        in.close();
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String WRITE_OBJECT_SQL = "BEGIN " + "  INSERT INTO java_objects(object_id, object_name, object_value) "
            + "  VALUES (?, ?, empty_blob()) " + "  RETURN object_value INTO ?; " + "END;";
    String READ_OBJECT_SQL = "SELECT object_value FROM java_objects WHERE object_id = ?";

    Connection conn = getOracleConnection();
    conn.setAutoCommit(false);/*from  w  w w .ja  v  a 2  s . c  o m*/
    List<Object> list = new ArrayList<Object>();
    list.add("This is a short string.");
    list.add(new Integer(1234));
    list.add(new java.util.Date());

    // write object to Oracle
    long id = 0001;
    String className = list.getClass().getName();
    CallableStatement cstmt = conn.prepareCall(WRITE_OBJECT_SQL);

    cstmt.setLong(1, id);
    cstmt.setString(2, className);

    cstmt.registerOutParameter(3, java.sql.Types.BLOB);

    cstmt.executeUpdate();
    BLOB blob = (BLOB) cstmt.getBlob(3);
    OutputStream os = blob.getBinaryOutputStream();
    ObjectOutputStream oop = new ObjectOutputStream(os);
    oop.writeObject(list);
    oop.flush();
    oop.close();
    os.close();

    // Read object from oracle
    PreparedStatement pstmt = conn.prepareStatement(READ_OBJECT_SQL);
    pstmt.setLong(1, id);
    ResultSet rs = pstmt.executeQuery();
    rs.next();
    InputStream is = rs.getBlob(1).getBinaryStream();
    ObjectInputStream oip = new ObjectInputStream(is);
    Object object = oip.readObject();
    className = object.getClass().getName();
    oip.close();
    is.close();
    rs.close();
    pstmt.close();
    conn.commit();

    // de-serialize list a java object from a given objectID
    List listFromDatabase = (List) object;
    System.out.println("[After De-Serialization] list=" + listFromDatabase);
    conn.close();
}

From source file:ComplexCompany.java

public static void main(String args[]) throws Exception {
    ServerSocket servSocket;// www. j a v  a 2  s.c  om
    Socket fromClientSocket;
    int cTosPortNumber = 1777;
    String str;
    ComplexCompany comp;

    servSocket = new ServerSocket(cTosPortNumber);
    System.out.println("Waiting for a connection on " + cTosPortNumber);

    fromClientSocket = servSocket.accept();

    ObjectOutputStream oos = new ObjectOutputStream(fromClientSocket.getOutputStream());

    ObjectInputStream ois = new ObjectInputStream(fromClientSocket.getInputStream());

    while ((comp = (ComplexCompany) ois.readObject()) != null) {
        comp.printCompanyObject();

        oos.writeObject("bye bye");
        break;
    }
    oos.close();

    fromClientSocket.close();
}