Example usage for java.io DataOutputStream DataOutputStream

List of usage examples for java.io DataOutputStream DataOutputStream

Introduction

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

Prototype

public DataOutputStream(OutputStream out) 

Source Link

Document

Creates a new data output stream to write data to the specified underlying output stream.

Usage

From source file:J2MEMixedRecordEnumerationExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*from  ww  w.ja  va 2s .c om*/
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
            byte[] outputRecord;
            String outputString[] = { "First Record", "Second Record", "Third Record" };
            int outputInteger[] = { 15, 10, 5 };
            boolean outputBoolean[] = { true, false, true };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeBoolean(outputBoolean[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
            }
            outputStream.reset();
            outputStream.close();
            outputDataStream.close();
            StringBuffer buffer = new StringBuffer();
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            recordEnumeration = recordstore.enumerateRecords(null, null, false);
            while (recordEnumeration.hasNextElement()) {
                recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                buffer.append(inputDataStream.readUTF());
                buffer.append("\n");
                buffer.append(inputDataStream.readBoolean());
                buffer.append("\n");
                buffer.append(inputDataStream.readInt());
                buffer.append("\n");
                alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
            inputStream.close();
            recordstore.closeRecordStore();
            if (RecordStore.listRecordStores() != null) {
                RecordStore.deleteRecordStore("myRecordStore");
                recordEnumeration.destroy();
            }
        } catch (Exception error) {
            alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
    }

}

From source file:eu.delving.sip.files.ReportWriter.java

public ReportWriter(File reportFile, File reportIndexFile, LinkCheckExtractor linkCheckExtractor)
        throws FileNotFoundException, XPathExpressionException, UnsupportedEncodingException {
    this.reportFile = reportFile;
    this.reportIndexFile = reportIndexFile;
    this.linkCheckExtractor = linkCheckExtractor;
    this.indexOut = new DataOutputStream(new FileOutputStream(reportIndexFile));
    this.count = new CountingOutputStream(new FileOutputStream(reportFile));
    this.out = new OutputStreamWriter(count, "UTF-8");
}

From source file:TaxSvc.TaxSvc.java

public GetTaxResult GetTax(GetTaxRequest req) {

    //Create URL/*w w  w .j a v a2 s . c o  m*/
    String taxget = svcURL + "/1.0/tax/get";
    URL url;

    HttpURLConnection conn;
    try {
        //Connect to URL with authorization header, request content.
        url = new URL(taxget);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);

        String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content
        conn.setRequestProperty("Authorization", encoded); //Add authorization header
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null
        String content = mapper.writeValueAsString(req);
        //System.out.println(content);   //Uncomment to see the content of the request object
        conn.setRequestProperty("Content-Length", Integer.toString(content.length()));

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(content);
        wr.flush();
        wr.close();

        conn.disconnect();

        if (conn.getResponseCode() != 200) //If we didn't get a success back, print out the error.
        {
            GetTaxResult res = mapper.readValue(conn.getErrorStream(), GetTaxResult.class); //Deserializes the response
            return res;
        }

        else //Otherwise, print out the total tax calculated
        {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            GetTaxResult res = mapper.readValue(conn.getInputStream(), GetTaxResult.class); //Deserializes the response
            return res;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
}

From source file:J2MESearchMixedRecordDataTypeExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*from ww w .j av a  2  s.  c  o m*/
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
            byte[] outputRecord;
            String outputString[] = { "A", "B", "M" };
            int outputInteger[] = { 15, 10, 5 };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
                outputStream.reset();
            }
            outputStream.close();
            outputDataStream.close();
            String inputString;
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            if (recordstore.getNumRecords() > 0) {
                filter = new Filter("Mary");
                recordEnumeration = recordstore.enumerateRecords(filter, null, false);
                while (recordEnumeration.hasNextElement()) {
                    recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                    inputString = inputDataStream.readUTF() + " " + inputDataStream.readInt();
                    alert = new Alert("Reading", inputString, null, AlertType.WARNING);
                    alert.setTimeout(Alert.FOREVER);
                    display.setCurrent(alert);
                }
            }
            inputStream.close();
            recordstore.closeRecordStore();
            if (RecordStore.listRecordStores() != null) {
                RecordStore.deleteRecordStore("myRecordStore");
                filter.filterClose();
                recordEnumeration.destroy();
            }
        } catch (Exception error) {
            alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
    }
}

From source file:io.lavagna.model.CardFullWithCounts.java

private static String hash(CardFullWithCounts cwc) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream daos = new DataOutputStream(baos);

    try {//from   w w  w  . j a v  a  2 s.  c  o  m
        // card
        daos.writeChars(Integer.toString(cwc.getId()));

        writeNotNull(daos, cwc.getName());
        writeInts(daos, cwc.getSequence(), cwc.getOrder(), cwc.getColumnId(), cwc.getUserId());
        // end card
        writeNotNull(daos, cwc.creationUser);
        writeNotNull(daos, cwc.creationDate);

        if (cwc.counts != null) {
            for (Map.Entry<String, CardDataCount> count : cwc.counts.entrySet()) {
                writeNotNull(daos, count.getKey());
                CardDataCount dataCount = count.getValue();
                daos.writeChars(Integer.toString(dataCount.getCardId()));
                if (dataCount.getCount() != null) {
                    daos.writeChars(Long.toString(dataCount.getCount().longValue()));
                }
                writeNotNull(daos, dataCount.getType());
            }
        }
        for (LabelAndValue lv : cwc.labels) {
            //
            writeInts(daos, lv.getLabelId(), lv.getLabelProjectId());
            writeNotNull(daos, lv.getLabelName());
            writeInts(daos, lv.getLabelColor());
            writeEnum(daos, lv.getLabelType());
            writeEnum(daos, lv.getLabelDomain());
            //
            writeInts(daos, lv.getLabelValueId(), lv.getLabelValueCardId(), lv.getLabelValueLabelId());
            writeNotNull(daos, lv.getLabelValueUseUniqueIndex());
            writeEnum(daos, lv.getLabelValueType());
            writeNotNull(daos, lv.getLabelValueString());
            writeNotNull(daos, lv.getLabelValueTimestamp());
            writeNotNull(daos, lv.getLabelValueInt());
            writeNotNull(daos, lv.getLabelValueCard());
            writeNotNull(daos, lv.getLabelValueUser());
        }
        daos.flush();

        return DigestUtils.sha256Hex(new ByteArrayInputStream(baos.toByteArray()));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.knewton.mapreduce.io.StudentEventWritableTest.java

@Test
public void testSerialization() throws DecoderException, TException, IOException {
    byte[] studentEventDataBytes = Hex.decodeHex(eventDataString.toCharArray());
    StudentEventData studentEventData = new StudentEventData();
    deserializer.deserialize(studentEventData, studentEventDataBytes);
    StudentEvent studentEvent = new StudentEvent(1, studentEventData);
    StudentEventWritable sew = new StudentEventWritable(studentEvent, 10L);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(byteArrayOutputStream);
    sew.write(dout);/*from   ww w. j  av a  2s . co  m*/

    StudentEventWritable deserializedWritable = new StudentEventWritable();
    InputStream is = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    DataInputStream dis = new DataInputStream(is);
    deserializedWritable.readFields(dis);
    assertEquals(sew.getStudentEvent(), deserializedWritable.getStudentEvent());
    assertEquals(sew.getTimestamp(), deserializedWritable.getTimestamp());
}

From source file:J2MESortMixedRecordDataTypeExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);//w  w  w . j ava 2  s  . c  o m
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
            byte[] outputRecord;
            String outputString[] = { "Mary", "Bob", "Adam" };
            int outputInteger[] = { 15, 10, 5 };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
                outputStream.reset();
            }
            outputStream.close();
            outputDataStream.close();

            String[] inputString = new String[3];
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            StringBuffer buffer = new StringBuffer();
            comparator = new Comparator();
            recordEnumeration = recordstore.enumerateRecords(null, comparator, false);
            while (recordEnumeration.hasNextElement()) {
                recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                buffer.append(inputDataStream.readUTF());
                buffer.append(inputDataStream.readInt());
                buffer.append("\n");
                inputDataStream.reset();
            }
            alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
            inputDataStream.close();
            inputStream.close();
            recordstore.closeRecordStore();
            if (RecordStore.listRecordStores() != null) {
                RecordStore.deleteRecordStore("myRecordStore");
                comparator.compareClose();
                recordEnumeration.destroy();
            }
        } catch (Exception error) {
            alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
    }
}

From source file:epn.edu.ec.bibliotecadigital.servidor.ServerRunnable.java

@Override
public void run() {
    try {//from w w  w  . ja  v a 2s .com
        DataInputStream dataIn = new DataInputStream(clientSocket.getInputStream());
        DataOutputStream dataOut = new DataOutputStream(clientSocket.getOutputStream());
        OutputStream out;
        String accion = dataIn.readUTF();
        Libro lbr;
        String nombreUsuario = dataIn.readUTF();
        System.out.println("nombreUsuario" + nombreUsuario);
        switch (accion) {
        case "bajar":

            String codArchivo = dataIn.readUTF();
            dataOut = new DataOutputStream(clientSocket.getOutputStream());

            lbr = new LibroJpaController(emf).findLibro(Integer.parseInt(codArchivo));
            if (lbr == null) {
                dataOut.writeBoolean(false);
                break;
            }
            dataOut.writeBoolean(true);

            //File file = new File("C:\\Computacion Distribuida\\" + lbr.getNombre());
            dataOut.writeUTF(lbr.getNombre());
            out = clientSocket.getOutputStream();
            try {
                byte[] bytes = new byte[64 * 1024];
                InputStream in = new ByteArrayInputStream(lbr.getArchivo());

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                Usuariolibros usrLbr = new Usuariolibros();
                usrLbr.setFecha(Calendar.getInstance().getTime());
                usrLbr.setAccion('B');
                usrLbr.setCodigolibro(lbr);
                usrLbr.setNombrecuenta(new Usuario(nombreUsuario));
                new UsuariolibrosJpaController(emf).create(usrLbr);
                in.close();
            } finally {
                IOUtils.closeQuietly(out);
            }
            break;
        case "subir":
            dataIn = new DataInputStream(clientSocket.getInputStream());
            String fileName = dataIn.readUTF();
            InputStream in = clientSocket.getInputStream();
            try {
                out = new FileOutputStream("C:\\Computacion Distribuida\\" + fileName);
                byte[] bytes = new byte[64 * 1024];

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                out.close();
                lbr = new Libro();
                lbr.setNombre(fileName);
                lbr.setArchivo(
                        IOUtils.toByteArray(new FileInputStream("C:\\Computacion Distribuida\\" + fileName)));

                new LibroJpaController(emf).create(lbr);
                Usuariolibros usrLbr = new Usuariolibros();
                usrLbr.setFecha(Calendar.getInstance().getTime());
                usrLbr.setAccion('S');
                usrLbr.setCodigolibro(lbr);
                usrLbr.setNombrecuenta(new Usuario(nombreUsuario));
                new UsuariolibrosJpaController(emf).create(usrLbr);
                actualizarLibrosEnServidores(fileName);
            } finally {
                IOUtils.closeQuietly(in);
            }
            break;
        case "obtenerLista":
            ObjectOutputStream outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
            outToServer.writeObject(new LibroJpaController(emf).findLibroEntities());
            outToServer.close();
            break;
        case "verificarEstado":
            dataOut.writeUTF(String.valueOf(server.isDisponible()));
            break;
        case "actualizar":
            dataIn = new DataInputStream(clientSocket.getInputStream());
            String fileNameFromServer = dataIn.readUTF();
            in = clientSocket.getInputStream();
            try {
                out = new FileOutputStream("C:\\Computacion Distribuida\\" + fileNameFromServer);
                byte[] bytes = new byte[64 * 1024];

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(in);
            }

        }
        dataIn.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.example.jarida.http.AsyncConnection.java

@Override
public String doInBackground(String... params) {
    final String method = params[0];
    final String urlString = params[1];

    final StringBuilder builder = new StringBuilder();

    try {//from   www  .j  a  v  a 2  s .com
        final URL url = new URL(urlString);

        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);

        if (method.equals(METHOD_POST)) {
            final String urlParams = params[2];
            conn.setRequestProperty(HTTP.CONTENT_LEN, "" + Integer.toString(urlParams.getBytes().length));
            System.out.println(urlParams);
            // Send request
            final DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(urlParams);
            wr.flush();
            wr.close();
        }

        // Get Response
        final InputStream is = conn.getInputStream();
        final BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        String line;
        while ((line = rd.readLine()) != null) {
            builder.append(line);
        }
        rd.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return builder.toString();
}

From source file:ai.eve.volley.request.JsonRequest.java

@Override
public void getBody(HttpURLConnection connection) {
    try {//from   ww w  .ja  v  a 2 s .c  o m
        if (mRequestBody != null) {
            connection.setDoOutput(true);
            connection.addRequestProperty(HTTP.CONTENT_TYPE, getBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(mRequestBody.getBytes(PROTOCOL_CHARSET));
            out.close();
        }
    } catch (UnsupportedEncodingException uee) {
        NetroidLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody,
                PROTOCOL_CHARSET);
    } catch (IOException e) {
        e.printStackTrace();
    }
}