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:Person.java

public static void main(String[] args) throws Exception {
    ObjectOutputStream outputStream = null;

    outputStream = new ObjectOutputStream(new FileOutputStream("yourFile.dat"));

    Person person = new Person();
    person.setFirstName("A");
    person.setLastName("B");
    person.setAge(38);//  w w  w.j  av  a 2s .  co m
    outputStream.writeObject(person);

    person = new Person();
    person.setFirstName("C");
    person.setLastName("D");
    person.setAge(22);
    outputStream.writeObject(person);
}

From source file:Main.java

public static void main(String args[]) throws IOException, ClassNotFoundException {
    File file = new File("test.txt");
    FileOutputStream outFile = new FileOutputStream(file);
    ObjectOutputStream outStream = new ObjectOutputStream(outFile);
    TestClass1 t1 = new TestClass1(true, 9, 'A', 0.0001, "java");
    TestClass2 t2 = new TestClass2();
    String t3 = "This is a test.";
    Date t4 = new Date();
    outStream.writeObject(t1);
    outStream.writeObject(t2);/*  w w w .  ja  v a2  s  .c  o  m*/
    outStream.writeObject(t3);
    outStream.writeObject(t4);
    outStream.close();
    outFile.close();
    FileInputStream inFile = new FileInputStream(file);
    ObjectInputStream inStream = new ObjectInputStream(inFile);
    System.out.println(inStream.readObject());
    System.out.println(inStream.readObject());
    System.out.println(inStream.readObject());
    System.out.println(inStream.readObject());
    inStream.close();
    inFile.close();
    file.delete();
}

From source file:com.artofsolving.jodconverter.XmlDocumentFormatRegistry.java

/**
 * Prints out a document-formats.xml from the {@link DefaultDocumentFormatRegistry}
 *///from   w  ww . ja  v a2 s.  com
public static void main(String[] args) throws IOException {
    DefaultDocumentFormatRegistry registry = new DefaultDocumentFormatRegistry();
    XStream xstream = createXStream();
    ObjectOutputStream outputStream = xstream.createObjectOutputStream(new OutputStreamWriter(System.out),
            "document-formats");
    for (Iterator iterator = registry.getDocumentFormats().iterator(); iterator.hasNext();) {
        outputStream.writeObject(iterator.next());
    }
    outputStream.close();
}

From source file:SerialVersionUID.java

/**
 * Generate a mapping of the serial version UIDs for the serializable classes
 * under the jboss dist directory//from   w  w w .  j  ava  2s .c o  m
 * 
 * @param args -
 *          [0] = jboss dist root directory
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.err.println("Usage: jboss-home | -rihome ri-home");
        System.exit(1);
    }
    File distHome = new File(args[0]);
    Map classVersionMap = null;
    if (args.length == 2)
        classVersionMap = generateRISerialVersionUIDReport(distHome);
    else
        classVersionMap = generateJBossSerialVersionUIDReport(distHome);
    // Write the map out the object file
    log.info("Total classes with serialVersionUID != 0: " + classVersionMap.size());
    FileOutputStream fos = new FileOutputStream("serialuid.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(classVersionMap);
    fos.close();
}

From source file:Cache.Servidor.java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    // Se calcula el tamao de las particiones del cache
    // de manera que la relacin sea
    // 25% Esttico y 75% Dinmico,
    // siendo la porcin dinmica particionada en 3 partes.

    Lector l = new Lector(); // Obtener tamao total del cache.
    int tamCache = l.leerTamCache("config.txt");
    //===================================
    int tamCaches = 0;
    if (tamCache % 4 == 0) { // Asegura que el nro sea divisible por 4.
        tamCaches = tamCache / 4;//from  w  w  w  .  j  a  v a2 s  . com
    } else { // Si no, suma para que lo sea.
        tamCaches = (tamCache - (tamCache) % 4 + 4) / 4;
    } // y divide por 4.

    System.out.println("Tamao total Cache: " + (int) tamCache); // imprimir tamao cache.
    System.out.println("Tamao particiones y parte esttica: " + tamCaches); // imprimir tamao particiones.
    //===================================

    lru_cache1 = new LRUCache(tamCaches); //Instanciar atributos.

    lru_cache2 = new LRUCache(tamCaches);
    lru_cache3 = new LRUCache(tamCaches);
    cestatico = new CacheEstatico(tamCaches);
    cestatico.addEntryToCache("query3", "respuesta cacheEstatico a query 3");
    cestatico.addEntryToCache("query7", "respuesta cacheEstatico a query 7");

    try {
        ServerSocket servidor = new ServerSocket(4500); // Crear un servidor en pausa hasta que un cliente llegue.
        while (true) {
            Socket clienteNuevo = servidor.accept();// Si llega se acepta.
            // Queda en pausa otra vez hasta que un objeto llegue.
            ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream());

            System.out.println("Objeto llego");
            //===================================
            Cache1 hilox1 = new Cache1(); // Instanciar hebras.
            Cache2 hilox2 = new Cache2();
            Cache3 hilox3 = new Cache3();

            // Leer el objeto, es un String.
            JSONObject request = (JSONObject) entrada.readObject();
            String b = (String) request.get("busqueda");

            //*************************Actualizar CACHE**************************************
            int actualizar = (int) request.get("actualizacion");
            // Si vienen el objeto que llego viene del Index es que va a actualizar el cache
            if (actualizar == 1) {
                int lleno = cestatico.lleno();
                if (lleno == 0) {
                    cestatico.addEntryToCache((String) request.get("busqueda"),
                            (String) request.get("respuesta"));
                } else {
                    // si el cache estatico esta lleno
                    //agrego l cache dinamico

                    if (hash(b) % 3 == 0) {
                        lru_cache1.addEntryToCache((String) request.get("busqueda"),
                                (String) request.get("respuesta"));
                    } else {
                        if (hash(b) % 3 == 1) {
                            lru_cache2.addEntryToCache((String) request.get("busqueda"),
                                    (String) request.get("respuesta"));

                        } else {
                            lru_cache3.addEntryToCache((String) request.get("busqueda"),
                                    (String) request.get("respuesta"));

                        }
                    }

                }
            } //***************************************************************
            else {

                // Para cada request del arreglo se distribuye
                // en Cache 1 2 o 3 segn su hash.
                JSONObject respuesta = new JSONObject();
                if (hash(b) % 3 == 0) {
                    respuesta = hilox1.fn(request); //Y corre la funcin de una hebra.
                } else {
                    if (hash(b) % 3 == 1) {
                        respuesta = hilox2.fn(request);
                    } else {
                        respuesta = hilox3.fn(request);
                    }
                }

                //RESPONDER DESDE EL SERVIDOR
                ObjectOutputStream resp = new ObjectOutputStream(clienteNuevo.getOutputStream());// obtengo el output del cliente para mandarle un msj
                resp.writeObject(respuesta);
                System.out.println("msj enviado desde el servidor");

                //clienteNuevo.close();
                //servidor.close();
            }

        }
    } catch (IOException ex) {
        Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:LoopingSocketServer.java

public static void main(String args[]) throws Exception {
    ServerSocket servSocket;//from w w  w. j  a v  a2  s.  co  m
    Socket fromClientSocket;
    int cTosPortNumber = 1777;
    String str;

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

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

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

    while ((str = (String) ois.readObject()) != null) {
        System.out.println("The message from client:  " + str);

        if (str.equals("bye")) {
            oos.writeObject("bye bye");
            break;
        } else {
            str = "Server returns " + str;
            oos.writeObject(str);
        }

    }
    oos.close();
    fromClientSocket.close();
}

From source file:ComplexCompany.java

public static void main(String args[]) throws Exception {
    ServerSocket servSocket;/*from  w  w  w . j  a va2 s  . co m*/
    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();
}

From source file:com.openteach.diamond.network.waverider.command.Command.java

public static void main(String[] args) {

    ByteArrayOutputStream bout = null;
    ObjectOutputStream objOutputStream = null;

    try {//from  w  w w. j  av a 2  s.  c o  m
        bout = new ByteArrayOutputStream();
        objOutputStream = new ObjectOutputStream(bout);
        SlaveState slaveState = new SlaveState();
        slaveState.setId(1L);
        slaveState.setIsMasterCandidate(false);
        objOutputStream.writeObject(slaveState);
        objOutputStream.flush();
        Command command = CommandFactory.createHeartbeatCommand(ByteBuffer.wrap(bout.toByteArray()));

        ByteBuffer buffer = command.marshall();
        Command cmd = Command.unmarshall(buffer);
        SlaveState ss = SlaveState.fromByteBuffer(cmd.getPayLoad());
        System.out.println(cmd.toString());
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (objOutputStream != null) {
                objOutputStream.close();
            }
            if (bout != null) {
                bout.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.icesoft.faces.webapp.parser.TagToComponentMap.java

/**
 * Main method for when this class is run to build the serialized data from
 * a set of TLDS./*from ww  w. j  a va 2 s  .c o m*/
 *
 * @param args The runtime arguements.
 */
public static void main(String args[]) {

    /* arg[0] is "new" to create serialzed data or 'old' to read serialized data
       arg[1] is filename for serialized data;
       arg[2...] are tld's to process */

    FileInputStream tldFile = null;

    TagToComponentMap map = new TagToComponentMap();

    if (args[0].equals("new")) {
        // Build new component map from tlds and serialize it;

        for (int i = 2; i < args.length; i++) {
            try {
                tldFile = new FileInputStream(args[i]);
                map.addTagAttrib((InputStream) tldFile);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }

        try {
            FileOutputStream fos = new FileOutputStream(args[1]);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(map);
            oos.flush();
            oos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (args[0].equals("old")) {
        // Build component from serialized data;
        try {
            FileInputStream fis = new FileInputStream(args[1]);
            ObjectInputStream ois = new ObjectInputStream(fis);
            map = (TagToComponentMap) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (args[0].equals("facelets")) {
        // Build new component map from tld, and use that to
        //  generate a Facelets taglib.xml
        // args[0] is command
        // args[1] is output taglib.xml
        // args[2] is input tld

        try {
            FileWriter faceletsTaglibXmlWriter = new FileWriter(args[1]);
            String preamble = "<?xml version=\"1.0\"?>\n"
                    + "<facelet-taglib xmlns=\"http://java.sun.com/xml/ns/javaee\"\n"
                    + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
                    + "xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee "
                    + "http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd\"\n"
                    + "version=\"2.0\">\n";

            String trailer = "</facelet-taglib>\n";
            faceletsTaglibXmlWriter.write(preamble);

            map.setFaceletsTaglibXmlWriter(faceletsTaglibXmlWriter);
            tldFile = new FileInputStream(args[2]);
            map.addTagAttrib((InputStream) tldFile);

            faceletsTaglibXmlWriter.write(trailer);
            faceletsTaglibXmlWriter.flush();
            faceletsTaglibXmlWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }
}

From source file:guardar.en.base.de.datos.MainServidor.java

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

    Mongo mongo = new Mongo("localhost", 27017);

    // nombre de la base de datos
    DB database = mongo.getDB("paginas");
    // coleccion de la db
    DBCollection collection = database.getCollection("indice");
    DBCollection collection_textos = database.getCollection("tabla");
    ArrayList<String> lista_textos = new ArrayList();

    try {/*from  w w  w  .j  a va  2  s. c o m*/
        ServerSocket servidor = new ServerSocket(4545); // Crear un servidor en pausa hasta que un cliente llegue.
        while (true) {
            String aux = new String();
            lista_textos.clear();
            Socket clienteNuevo = servidor.accept();// Si llega se acepta.
            // Queda en pausa otra vez hasta que un objeto llegue.
            ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream());

            JSONObject request = (JSONObject) entrada.readObject();
            String b = (String) request.get("id");
            //hacer una query a la base de datos con la palabra que se quiere obtener

            BasicDBObject query = new BasicDBObject("palabra", b);
            DBCursor cursor = collection.find(query);
            ArrayList<DocumentosDB> lista_doc = new ArrayList<>();
            // de la query tomo el campo documentos y los agrego a una lista
            try {
                while (cursor.hasNext()) {
                    //System.out.println(cursor.next());
                    BasicDBList campo_documentos = (BasicDBList) cursor.next().get("documentos");
                    // en el for voy tomando uno por uno los elementos en el campo documentos
                    for (Iterator<Object> it = campo_documentos.iterator(); it.hasNext();) {
                        BasicDBObject dbo = (BasicDBObject) it.next();
                        //DOC tiene id y frecuencia
                        DocumentosDB doc = new DocumentosDB();
                        doc.makefn2(dbo);
                        //int id = (int)doc.getId_documento();
                        //int f = (int)doc.getFrecuencia();

                        lista_doc.add(doc);

                        //*******************************************

                        //********************************************

                        //QUERY A LA COLECCION DE TEXTOS
                        /* BasicDBObject query_textos = new BasicDBObject("id", doc.getId_documento());//query
                         DBCursor cursor_textos = collection_textos.find(query_textos);
                         try {
                        while (cursor_textos.hasNext()) {
                                    
                                    
                            DBObject obj = cursor_textos.next();
                                
                            String titulo = (String) obj.get("titulo");
                            titulo = titulo + "\n\n";
                            String texto = (String) obj.get("texto");
                                
                            String texto_final = titulo + texto;
                            aux = texto_final;
                            lista_textos.add(texto_final);
                        }
                         } finally {
                        cursor_textos.close();
                         }*/
                        //System.out.println(doc.getId_documento());
                        //System.out.println(doc.getFrecuencia());

                    } // end for

                } //end while query

            } finally {
                cursor.close();
            }

            // ordeno la lista de menor a mayor
            Collections.sort(lista_doc, new Comparator<DocumentosDB>() {

                @Override
                public int compare(DocumentosDB o1, DocumentosDB o2) {
                    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                    return o1.getFrecuencia().compareTo(o2.getFrecuencia());
                }
            });
            int tam = lista_doc.size() - 1;
            for (int j = tam; j >= 0; j--) {

                BasicDBObject query_textos = new BasicDBObject("id",
                        (int) lista_doc.get(j).getId_documento().intValue());//query
                DBCursor cursor_textos = collection_textos.find(query_textos);// lo busco
                try {
                    while (cursor_textos.hasNext()) {

                        DBObject obj = cursor_textos.next();
                        String titulo = "*******************************";
                        titulo += (String) obj.get("titulo");
                        int f = (int) lista_doc.get(j).getFrecuencia().intValue();
                        String strinf = Integer.toString(f);
                        titulo += "******************************* frecuencia:" + strinf;
                        titulo = titulo + "\n\n";

                        String texto = (String) obj.get("texto");

                        String texto_final = titulo + texto + "\n\n";
                        aux = aux + texto_final;
                        //lista_textos.add(texto_final);
                    }
                } finally {
                    cursor_textos.close();
                }

            }

            //actualizar el cache
            try {
                Socket cliente_cache = new Socket("localhost", 4500); // nos conectamos con el servidor
                ObjectOutputStream mensaje_cache = new ObjectOutputStream(cliente_cache.getOutputStream()); // get al output del servidor, que es cliente : socket del cliente q se conecto al server
                JSONObject actualizacion_cache = new JSONObject();
                actualizacion_cache.put("actualizacion", 1);
                actualizacion_cache.put("busqueda", b);
                actualizacion_cache.put("respuesta", aux);
                mensaje_cache.writeObject(actualizacion_cache); // envio el msj al servidor
            } catch (Exception ex) {

            }

            //RESPONDER DESDE EL SERVIDORIndex al FRONT
            ObjectOutputStream resp = new ObjectOutputStream(clienteNuevo.getOutputStream());// obtengo el output del cliente para mandarle un msj
            resp.writeObject(aux);
            System.out.println("msj enviado desde el servidor");

        }
    } catch (IOException ex) {
        Logger.getLogger(MainServidor.class.getName()).log(Level.SEVERE, null, ex);
    }

}