Example usage for java.io ObjectOutputStream writeObject

List of usage examples for java.io ObjectOutputStream writeObject

Introduction

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

Prototype

public final void writeObject(Object obj) throws IOException 

Source Link

Document

Write the specified object to the ObjectOutputStream.

Usage

From source file:Shape.java

public static void main(String[] args) throws Exception {
    List shapeTypes, shapes;/*  w  ww.jav a2  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:Data.java

public static void main(String[] args) {
    Data data = new Data(1);
    try {/*from   www.  jav  a 2s .c  om*/
        ObjectOutputStream objectOut = new ObjectOutputStream(
                new BufferedOutputStream(new FileOutputStream("C:/test.bin")));
        objectOut.writeObject(data);
        System.out.println("1st Object written has value: " + data.getValue());
        data.setValue(2);
        objectOut.writeObject(data);
        System.out.println("2nd Object written has value: " + data.getValue());
        data.setValue(3);
        objectOut.writeObject(data);
        System.out.println("3rd Object written has value: " + data.getValue());
        objectOut.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
    try {
        ObjectInputStream objectIn = new ObjectInputStream(
                new BufferedInputStream(new FileInputStream("C:/test.bin")));
        Data data1 = (Data) objectIn.readObject();
        Data data2 = (Data) objectIn.readObject();
        Data data3 = (Data) objectIn.readObject();
        System.out.println(data1.equals(data2));
        System.out.println(data2.equals(data3));
        System.out.println(data1.getValue());
        System.out.println(data2.getValue());
        System.out.println(data3.getValue());
        objectIn.close();
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:ObjectStreamTest.java

public static void main(String[] args) {
    Employee harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);
    Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
    carl.setSecretary(harry);//from www  . ja v a2 s .  co m
    Manager tony = new Manager("Tony Tester", 40000, 1990, 3, 15);
    tony.setSecretary(harry);

    Employee[] staff = new Employee[3];

    staff[0] = carl;
    staff[1] = harry;
    staff[2] = tony;

    try {
        // save all employee records to the file employee.dat
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.dat"));
        out.writeObject(staff);
        out.close();

        // retrieve all records into a new array
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.dat"));
        Employee[] newStaff = (Employee[]) in.readObject();
        in.close();

        // raise secretary's salary
        newStaff[1].raiseSalary(10);

        // print the newly read employee records
        for (Employee e : newStaff)
            System.out.println(e);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:SignatureTest.java

public static void main(String[] args) {
    try {/*from  w  ww  .  ja va  2s. com*/
        if (args[0].equals("-genkeypair")) {
            KeyPairGenerator pairgen = KeyPairGenerator.getInstance("DSA");
            SecureRandom random = new SecureRandom();
            pairgen.initialize(KEYSIZE, random);
            KeyPair keyPair = pairgen.generateKeyPair();
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
            out.writeObject(keyPair.getPublic());
            out.close();
            out = new ObjectOutputStream(new FileOutputStream(args[2]));
            out.writeObject(keyPair.getPrivate());
            out.close();
        } else if (args[0].equals("-sign")) {
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            PrivateKey privkey = (PrivateKey) keyIn.readObject();
            keyIn.close();

            Signature signalg = Signature.getInstance("DSA");
            signalg.initSign(privkey);

            File infile = new File(args[1]);
            InputStream in = new FileInputStream(infile);
            int length = (int) infile.length();
            byte[] message = new byte[length];
            in.read(message, 0, length);
            in.close();

            signalg.update(message);
            byte[] signature = signalg.sign();

            DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2]));
            int signlength = signature.length;
            out.writeInt(signlength);
            out.write(signature, 0, signlength);
            out.write(message, 0, length);
            out.close();
        } else if (args[0].equals("-verify")) {
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[2]));
            PublicKey pubkey = (PublicKey) keyIn.readObject();
            keyIn.close();

            Signature verifyalg = Signature.getInstance("DSA");
            verifyalg.initVerify(pubkey);

            File infile = new File(args[1]);
            DataInputStream in = new DataInputStream(new FileInputStream(infile));
            int signlength = in.readInt();
            byte[] signature = new byte[signlength];
            in.read(signature, 0, signlength);

            int length = (int) infile.length() - signlength - 4;
            byte[] message = new byte[length];
            in.read(message, 0, length);
            in.close();

            verifyalg.update(message);
            if (!verifyalg.verify(signature))
                System.out.print("not ");
            System.out.println("verified");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Shape.java

public static void main(String[] args) throws Exception {
    List shapeTypes, shapes;// w  w  w.  ja  va 2  s  .co m
    if (args.length == 0) {
        shapeTypes = new ArrayList();
        shapes = new ArrayList();
        // Add references to the class objects:
        shapeTypes.add(Circle.class);
        shapeTypes.add(Square.class);
        shapeTypes.add(Line.class);
        // Make some shapes:
        for (int i = 0; i < 10; i++)
            shapes.add(Shape.randomFactory());
        // Set all the static colors to GREEN:
        for (int i = 0; i < 10; i++)
            ((Shape) shapes.get(i)).setColor(Shape.GREEN);
        // Save the state vector:
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("CADState.out"));
        out.writeObject(shapeTypes);
        Line.serializeStaticState(out);
        out.writeObject(shapes);
    } else { // There's a command-line argument
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(args[0]));
        // Read in the same order they were written:
        shapeTypes = (List) in.readObject();
        Line.deserializeStaticState(in);
        shapes = (List) in.readObject();
    }
    // Display the shapes:
    System.out.println(shapes);
}

From source file:net.java.sen.tools.MkCompoundTable.java

/**
 * Build compound word table./* w  w  w  .j  a v  a 2s  .  co  m*/
 */
public static void main(String args[]) {
    ResourceBundle rb = ResourceBundle.getBundle("dictionary");
    int pos_start = Integer.parseInt(rb.getString("pos_start"));
    int pos_size = Integer.parseInt(rb.getString("pos_size"));

    try {
        log.info("reading compound word information ... ");
        HashMap compoundTable = new HashMap();

        log.info("load dic: " + rb.getString("compound_word_file"));
        BufferedReader dicStream = new BufferedReader(new InputStreamReader(
                new FileInputStream(rb.getString("compound_word_file")), rb.getString("dic.charset")));

        String t;
        int line = 0;

        StringBuffer pos_b = new StringBuffer();
        while ((t = dicStream.readLine()) != null) {
            CSVParser parser = new CSVParser(t);
            String csv[] = parser.nextTokens();
            if (csv.length < (pos_size + pos_start)) {
                throw new RuntimeException("format error:" + line);
            }

            pos_b.setLength(0);
            for (int i = pos_start; i < (pos_start + pos_size - 1); i++) {
                pos_b.append(csv[i]);
                pos_b.append(',');
            }

            pos_b.append(csv[pos_start + pos_size - 1]);
            pos_b.append(',');

            for (int i = pos_start + pos_size; i < (csv.length - 2); i++) {
                pos_b.append(csv[i]);
                pos_b.append(',');
            }
            pos_b.append(csv[csv.length - 2]);
            compoundTable.put(pos_b.toString(), csv[csv.length - 1]);
        }
        dicStream.close();
        log.info("done.");
        log.info("writing compound word table ... ");
        ObjectOutputStream os = new ObjectOutputStream(
                new FileOutputStream(rb.getString("compound_word_table")));
        os.writeObject(compoundTable);
        os.close();
        log.info("done.");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

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   w  w  w .  j  a  v  a2 s.c  om
        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:ObjectStreams.java

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

    ObjectOutputStream out = null;
    try {//from   w w w  .  java  2s.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: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//from   ww w.  j a v a2  s.  com
        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:MainClass.java

public static void main(String[] args) throws Exception {
    ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("clients.ser"));

    AccountRecordSerializable record;/*  ww  w.  ja  v  a 2s . c  o m*/

    record = new AccountRecordSerializable(1, "firstName", "lastName", 0.1);
    output.writeObject(record);

    output.close();
}