Example usage for java.io ObjectOutputStream close

List of usage examples for java.io ObjectOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the stream.

Usage

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 va  2 s. c o  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: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);//  w ww  .j av  a  2  s  .co  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: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);//w w w . ja va  2s  .  com
    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:TestCipher.java

public static void main(String args[]) throws Exception {
    Set set = new HashSet();
    Random random = new Random();
    for (int i = 0; i < 10; i++) {
        Point point = new Point(random.nextInt(1000), random.nextInt(2000));
        set.add(point);//from   www.j a  va2s  .  c  o  m
    }
    int last = random.nextInt(5000);

    // Create Key
    byte key[] = password.getBytes();
    DESKeySpec desKeySpec = new DESKeySpec(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

    // Create Cipher
    Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    desCipher.init(Cipher.ENCRYPT_MODE, secretKey);

    // Create stream
    FileOutputStream fos = new FileOutputStream("out.des");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    CipherOutputStream cos = new CipherOutputStream(bos, desCipher);
    ObjectOutputStream oos = new ObjectOutputStream(cos);

    // Write objects
    oos.writeObject(set);
    oos.writeInt(last);
    oos.flush();
    oos.close();

    // Change cipher mode
    desCipher.init(Cipher.DECRYPT_MODE, secretKey);

    // Create stream
    FileInputStream fis = new FileInputStream("out.des");
    BufferedInputStream bis = new BufferedInputStream(fis);
    CipherInputStream cis = new CipherInputStream(bis, desCipher);
    ObjectInputStream ois = new ObjectInputStream(cis);

    // Read objects
    Set set2 = (Set) ois.readObject();
    int last2 = ois.readInt();
    ois.close();

    // Compare original with what was read back
    int count = 0;
    if (set.equals(set2)) {
        System.out.println("Set1: " + set);
        System.out.println("Set2: " + set2);
        System.out.println("Sets are okay.");
        count++;
    }
    if (last == last2) {
        System.out.println("int1: " + last);
        System.out.println("int2: " + last2);
        System.out.println("ints are okay.");
        count++;
    }
    if (count != 2) {
        System.out.println("Problem during encryption/decryption");
    }
}

From source file:SignatureTest.java

public static void main(String[] args) {
    try {/*from w w  w.  j  a v a2  s .  c  o  m*/
        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:MyClass.java

public static void main(String[] argv) throws Exception {
    double v[] = { 1.1, 2.2, 3.3 };
    double v2[] = { 9.0, 8.0, 7.7 };

    MyClass obj1 = new MyClass("This is a test", v, "Test.txt");
    MyClass obj2 = new MyClass("Alpha Beta Gamma", v2, "Sample.dat");

    ObjectOutputStream fout = new ObjectOutputStream(new FileOutputStream("obj.dat"));
    System.out.println("obj1:\n" + obj1);
    fout.writeObject(obj1);//ww w  .  j a  v  a2 s  . c om
    System.out.println("obj2:\n" + obj2);
    fout.writeObject(obj2);
    fout.close();

    ObjectInputStream fin = new ObjectInputStream(new FileInputStream("obj.dat"));
    MyClass inputObj;

    inputObj = (MyClass) fin.readObject();
    System.out.println("First object:\n" + inputObj);

    inputObj = (MyClass) fin.readObject();
    System.out.println("Second object:\n" + inputObj);
    fin.close();
}

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

/**
 * Build compound word table.//  ww w .  j ava  2  s. c  o  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:MainClass.java

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

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

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

    output.close();
}

From source file:com.puffywhiteshare.PWSApp.java

/**
 * @param args/*from w  w  w .  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:Main.java

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

    ObjectOutputStream out = new ObjectOutputStream(
            new BufferedOutputStream(new FileOutputStream("file.data")));

    out.writeObject(Calendar.getInstance());
    out.writeObject(new BigDecimal("123.123"));
    out.writeInt(1);//from ww  w .  j a  v  a2s  .c o  m
    out.writeUTF("tutorial");
    out.close();

    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream("file.data")));

    BigDecimal price;
    int unit;
    String desc;

    Calendar date = (Calendar) in.readObject();
    System.out.println(date);

    price = (BigDecimal) in.readObject();
    unit = in.readInt();
    desc = in.readUTF();
    System.out.println(unit);
    System.out.println(desc);
    System.out.println(price);
    in.close();
}