Example usage for java.io DataOutputStream writeInt

List of usage examples for java.io DataOutputStream writeInt

Introduction

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

Prototype

public final void writeInt(int v) throws IOException 

Source Link

Document

Writes an int to the underlying output stream as four bytes, high byte first.

Usage

From source file:WriteReadMixedDataTypesExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*w  ww .ja v a2 s  . c  om*/
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            byte[] outputRecord;
            String outputString = "First Record";
            int outputInteger = 15;
            boolean outputBoolean = true;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            outputDataStream.writeUTF(outputString);
            outputDataStream.writeBoolean(outputBoolean);
            outputDataStream.writeInt(outputInteger);
            outputDataStream.flush();
            outputRecord = outputStream.toByteArray();
            recordstore.addRecord(outputRecord, 0, outputRecord.length);
            outputStream.reset();
            outputStream.close();
            outputDataStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            String inputString = null;
            int inputInteger = 0;
            boolean inputBoolean = false;
            byte[] byteInputData = new byte[100];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            for (int x = 1; x <= recordstore.getNumRecords(); x++) {
                recordstore.getRecord(x, byteInputData, 0);
                inputString = inputDataStream.readUTF();
                inputBoolean = inputDataStream.readBoolean();
                inputInteger = inputDataStream.readInt();
                inputStream.reset();
            }
            inputStream.close();
            inputDataStream.close();
            alert = new Alert("Reading", inputString + " " + inputInteger + " " + inputBoolean, null,
                    AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        } catch (Exception error) {
            alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            recordstore.closeRecordStore();
        } catch (Exception error) {
            alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore("myRecordStore");
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}

From source file:RMSGameScores.java

/**
 * Add a new score to the storage.//  www.  j a  va2  s .  c o  m
 * 
 * @param score
 *            the score to store.
 * @param playerName
 *            the name of the play achieving this score.
 */
public void addScore(int score, String playerName) {
    // Each score is stored in a separate record, formatted with
    // the score, followed by the player name.
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream outputStream = new DataOutputStream(baos);
    try {
        // Push the score into a byte array.
        outputStream.writeInt(score);
        // Then push the player name.
        outputStream.writeUTF(playerName);
    } catch (IOException ioe) {
        System.out.println(ioe);
        ioe.printStackTrace();
    }

    // Extract the byte array
    byte[] b = baos.toByteArray();
    try {
        // Add it to the record store
        recordStore.addRecord(b, 0, b.length);
    } catch (RecordStoreException rse) {
        System.out.println(rse);
        rse.printStackTrace();
    }
}

From source file:com.facebook.infrastructure.db.Row.java

public void serialize(Row row, DataOutputStream dos) throws IOException {
    dos.writeUTF(row.key());/* w  ww.j  a v  a2s  . c om*/
    Map<String, ColumnFamily> columnFamilies = row.getColumnFamilyMap();
    int size = columnFamilies.size();
    dos.writeInt(size);

    if (size > 0) {
        Set<String> cNames = columnFamilies.keySet();
        for (String cName : cNames) {
            ColumnFamily.serializer().serialize(columnFamilies.get(cName), dos);
        }
    }
}

From source file:org.gitools.matrix.format.CmatrixMatrixFormat.java

@Override
protected void writeResource(IResourceLocator resourceLocator, IMatrix resource,
        IProgressMonitor progressMonitor) throws PersistenceException {

    if (!(resource instanceof CompressMatrix)) {
        throw new UnsupportedOperationException("It is not possible to convert into a compress matrix");
    }/*from w ww .j  a  v  a  2  s . co  m*/

    CompressMatrix matrix = (CompressMatrix) resource;

    try {

        DataOutputStream out = new DataOutputStream(resourceLocator.openOutputStream(progressMonitor));

        int formatVersion = 0;
        out.writeInt(0);

        progressMonitor.begin("Writing dictionary...", 1);
        byte[] dictionary = matrix.getDictionary();
        out.writeInt(dictionary.length);
        out.write(dictionary);

        progressMonitor.begin("Writing columns...", 1);
        byte[] buffer = AbstractCompressor.stringToByteArray(matrix.getColumns().getLabels());
        out.writeInt(buffer.length);
        out.write(buffer);

        progressMonitor.begin("Writing rows...", 1);
        buffer = AbstractCompressor.stringToByteArray(matrix.getRows().getLabels());
        out.writeInt(buffer.length);
        out.write(buffer);

        progressMonitor.begin("Writing headers...", 1);
        String[] headers = new String[resource.getLayers().size()];
        for (int i = 0; i < resource.getLayers().size(); i++) {
            headers[i] = resource.getLayers().get(i).getId();
        }
        buffer = AbstractCompressor.stringToByteArray(headers);
        out.writeInt(buffer.length);
        out.write(buffer);

        Map<Integer, CompressRow> compressRowMap = matrix.getCompressRows();
        progressMonitor.begin("Writing values...", compressRowMap.size());
        for (Map.Entry<Integer, CompressRow> value : compressRowMap.entrySet()) {
            progressMonitor.worked(1);

            // The row position
            out.writeInt(value.getKey());

            // Compress the row
            CompressRow compressRow = value.getValue();

            // Write the length of the buffer before compression
            out.writeInt(compressRow.getNotCompressedLength());

            // The length of the compressed buffer with the columns
            out.writeInt(compressRow.getContent().length);

            // The buffer with all the columns
            out.write(compressRow.getContent());
        }

        out.close();

    } catch (IOException e) {
        throw new PersistenceException(e);
    }
}

From source file:J2MEMixedRecordEnumerationExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*from  w w w. jav  a  2  s .c  o  m*/
        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:info.fetter.logstashforwarder.protocol.LumberjackClient.java

private int sendDataFrame(DataOutputStream output, Map<String, byte[]> keyValues) throws IOException {
    output.writeByte(PROTOCOL_VERSION);//from  w w  w . ja  v  a  2s  . co m
    output.writeByte(FRAME_DATA);
    output.writeInt(sequence++);
    output.writeInt(keyValues.size());
    int bytesSent = 10;
    for (String key : keyValues.keySet()) {
        int keyLength = key.length();
        output.writeInt(keyLength);
        bytesSent += 4;
        output.write(key.getBytes());
        bytesSent += keyLength;
        byte[] value = keyValues.get(key);
        output.writeInt(value.length);
        bytesSent += 4;
        output.write(value);
        bytesSent += value.length;
    }
    output.flush();
    return bytesSent;
}

From source file:org.apache.fop.render.pdf.pdfbox.PSPDFGraphics2D.java

@Override
public boolean drawImage(Image img, int x1, int y1, ImageObserver observer) {
    PSGenerator tmp = gen;/*from  www . j a  va  2 s .co  m*/
    if (gen instanceof PSDocumentHandler.FOPPSGenerator) {
        PSDocumentHandler.FOPPSGenerator fopGen = (PSDocumentHandler.FOPPSGenerator) tmp;
        PSDocumentHandler handler = fopGen.getHandler();
        if (handler.getPSUtil().isOptimizeResources()) {
            try {
                final int width = img.getWidth(observer);
                final int height = img.getHeight(observer);
                if (width == -1 || height == -1) {
                    return false;
                }
                BufferedImage buf = getImage(width, height, img, observer);
                if (buf == null) {
                    return false;
                }
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                DataBufferInt db = (DataBufferInt) buf.getRaster().getDataBuffer();
                DataOutputStream dos = new DataOutputStream(bos);
                dos.writeInt(width);
                dos.writeInt(height);
                for (int i : db.getData()) {
                    dos.writeInt(i);
                }
                String format = DataBufferInt.class.getName();
                int hash = Arrays.hashCode(bos.toByteArray());
                URI uri = fopGen.getImages().get(hash);
                if (uri == null) {
                    uri = new TempResourceURIGenerator("img" + hash + "." + format).generate();
                    fopGen.getImages().put(hash, uri);
                    BufferedOutputStream outputStream = fopGen.getTempStream(uri);
                    outputStream.write(bos.toByteArray());
                    outputStream.close();
                }
                PSResource form = handler.getFormForImage(uri.toASCIIString());
                ImageInfo info = new ImageInfo(uri.toASCIIString(), "image/" + format);
                ImageSize size = new ImageSize(width, height, handler.getUserAgent().getTargetResolution());
                size.calcSizeFromPixels();
                info.setSize(size);
                float res = handler.getUserAgent().getSourceResolution() / 72;
                Rectangle rect = new Rectangle(0, 0, (int) (size.getWidthMpt() * res),
                        (int) (size.getHeightMpt() * res));
                gen.saveGraphicsState();
                gen.concatMatrix(getTransform());
                writeClip(getClip());
                PSImageUtils.drawForm(form, info, rect, gen);
                gen.restoreGraphicsState();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return true;
        }
    }
    return super.drawImage(img, x1, y1, observer);
}

From source file:org.mrgeo.data.raster.RasterWritable.java

private static void writeHeader(final Raster raster, final OutputStream out) throws IOException {
    final DataOutputStream dos = new DataOutputStream(out);

    int headersize = HEADERSIZE;
    // this is in integers!
    // MAKE SURE TO KEEP THIS CORRECT IF YOU ADD PARAMETERS TO THE HEADER!!!

    final SampleModel model = raster.getSampleModel();
    final SampleModelType modeltype = toSampleModelType(model);

    int[] bandOffsets = null;
    switch (modeltype) {
    case BANDED://w w  w.  j  a  v  a2  s  .c o  m
        break;
    case PIXELINTERLEAVED:
    case COMPONENT:
        bandOffsets = ((ComponentSampleModel) model).getBandOffsets();

        // add pixel-stride, scanline-stride, band offset count, & band offsets to
        // the header count
        headersize += 3 + bandOffsets.length;
        break;
    case MULTIPIXELPACKED:
        break;
    case SINGLEPIXELPACKED:
        break;
    default:
    }

    dos.writeInt(headersize);
    dos.writeInt(raster.getHeight());
    dos.writeInt(raster.getWidth());
    dos.writeInt(raster.getNumBands());
    dos.writeInt(raster.getTransferType());

    dos.writeInt(modeltype.ordinal());

    switch (modeltype) {
    case BANDED:
        break;
    case COMPONENT:
    case PIXELINTERLEAVED: {
        final ComponentSampleModel pism = (ComponentSampleModel) model;
        dos.writeInt(pism.getPixelStride());
        dos.writeInt(pism.getScanlineStride());

        dos.writeInt(bandOffsets.length);
        for (final int bandOffset : bandOffsets) {
            dos.writeInt(bandOffset);
        }
    }
        break;
    case MULTIPIXELPACKED:
        break;
    case SINGLEPIXELPACKED:
        break;
    default:
    }

}

From source file:RealFunctionValidation.java

public static Object readAndWritePrimitiveValue(final DataInputStream in, final DataOutputStream out,
        final Class<?> type) throws IOException {

    if (!type.isPrimitive()) {
        throw new IllegalArgumentException("type must be primitive");
    }/*w w  w.j ava2 s. co m*/
    if (type.equals(Boolean.TYPE)) {
        final boolean x = in.readBoolean();
        out.writeBoolean(x);
        return Boolean.valueOf(x);
    } else if (type.equals(Byte.TYPE)) {
        final byte x = in.readByte();
        out.writeByte(x);
        return Byte.valueOf(x);
    } else if (type.equals(Character.TYPE)) {
        final char x = in.readChar();
        out.writeChar(x);
        return Character.valueOf(x);
    } else if (type.equals(Double.TYPE)) {
        final double x = in.readDouble();
        out.writeDouble(x);
        return Double.valueOf(x);
    } else if (type.equals(Float.TYPE)) {
        final float x = in.readFloat();
        out.writeFloat(x);
        return Float.valueOf(x);
    } else if (type.equals(Integer.TYPE)) {
        final int x = in.readInt();
        out.writeInt(x);
        return Integer.valueOf(x);
    } else if (type.equals(Long.TYPE)) {
        final long x = in.readLong();
        out.writeLong(x);
        return Long.valueOf(x);
    } else if (type.equals(Short.TYPE)) {
        final short x = in.readShort();
        out.writeShort(x);
        return Short.valueOf(x);
    } else {
        // This should never occur.
        throw new IllegalStateException();
    }
}

From source file:org.xenei.compressedgraph.SerializableNode.java

private void write(DataOutputStream os, String s) throws IOException {
    if (s == null) {
        os.writeInt(-1);
    } else {//ww w . j  av a 2s .c  om
        byte[] b = encodeString(s);
        os.writeInt(b.length);
        if (b.length > 0) {
            os.write(b);
        }
    }
}