Example usage for java.io DataOutputStream writeDouble

List of usage examples for java.io DataOutputStream writeDouble

Introduction

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

Prototype

public final void writeDouble(double v) throws IOException 

Source Link

Document

Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.

Usage

From source file:ch.unil.genescore.vegas.Snp.java

/** 
 * Write genotype information of this snp to the binary file. Format is:
 * 0. id_/*from ww w  .j a  v  a 2 s.c om*/
 * 1. genotypes_.length
 * 2. genotypes_[]
 * 3. maf_
 * 4. alleleMean_
 * 5. alleleSd_
 * @throws IOException 
 */
public void writeGenotype(DataOutputStream os) throws IOException {

    // NOTE: CHANGE ALSO readBinary() AND skip() WHEN CHANGING ANYTHING HERE!
    os.writeUTF(id_);

    for (int i = 0; i < genotypes_.length; i++)
        os.writeByte(genotypes_[i]);

    os.writeDouble(maf_);
    os.writeDouble(alleleMean_);
    os.writeDouble(alleleSd_);
}

From source file:au.org.ala.spatial.util.RecordsSmall.java

private void makeUniquePoints() throws Exception {
    //make unique points and index
    points = new RandomAccessFile(filename + "records.csv.small.points", "r");
    double[] allPoints = getPointsAll();
    Coord[] p = new Coord[allPoints.length / 2];
    for (int i = 0; i < allPoints.length; i += 2) {
        p[i / 2] = new Coord(allPoints[i], allPoints[i + 1], i / 2);
    }//from  w w w.j  a va2  s .co m
    allPoints = null; //make available to GC
    Arrays.sort(p, new Comparator<Coord>() {
        public int compare(Coord o1, Coord o2) {
            return o1.longitude == o2.longitude
                    ? (o1.latitude == o2.latitude ? 0 : (o1.latitude - o2.latitude > 0.0 ? 1 : -1))
                    : (o1.longitude - o2.longitude > 0.0 ? 1 : -1);
        }
    });

    DataOutputStream outputUniquePoints = new DataOutputStream(
            new BufferedOutputStream(new FileOutputStream(filename + "records.csv.small.pointsUniquePoints")));
    DataOutputStream outputUniqueIdx = new DataOutputStream(
            new BufferedOutputStream(new FileOutputStream(filename + "records.csv.small.pointsUniqueIdx")));

    int pos = -1; //first point is set after pos++
    int[] newPos = new int[p.length];
    for (int i = 0; i < p.length; i++) {
        if (i == 0 || p[i].latitude != p[i - 1].latitude || p[i].longitude != p[i - 1].longitude) {
            outputUniquePoints.writeDouble(p[i].latitude);
            outputUniquePoints.writeDouble(p[i].longitude);
            pos++;
        }
        newPos[p[i].pos] = pos;
    }
    for (int i = 0; i < p.length; i++) {
        outputUniqueIdx.writeInt(newPos[i]);
    }

    outputUniqueIdx.flush();
    outputUniqueIdx.close();
    outputUniquePoints.flush();
    outputUniquePoints.close();

    points.close();
}

From source file:org.apache.hadoop.io.TestArrayOutputStream.java

private void runComparison(ArrayOutputStream aos, DataOutputStream dos, ByteArrayOutputStream bos)
        throws IOException {
    Random r = new Random();
    // byte/*  w  ww .ja v a2s .c  o  m*/
    int b = r.nextInt(128);
    aos.write(b);
    dos.write(b);

    // byte[]
    byte[] bytes = new byte[10];
    r.nextBytes(bytes);
    aos.write(bytes, 0, 10);
    dos.write(bytes, 0, 10);

    // Byte
    aos.writeByte(b);
    dos.writeByte(b);

    // boolean
    boolean bool = r.nextBoolean();
    aos.writeBoolean(bool);
    dos.writeBoolean(bool);

    // short
    short s = (short) r.nextInt();
    aos.writeShort(s);
    dos.writeShort(s);

    // char
    int c = r.nextInt();
    aos.writeChar(c);
    dos.writeChar(c);

    // int
    int i = r.nextInt();
    aos.writeInt(i);
    dos.writeInt(i);

    // long
    long l = r.nextLong();
    aos.writeLong(l);
    dos.writeLong(l);

    // float
    float f = r.nextFloat();
    aos.writeFloat(f);
    dos.writeFloat(f);

    // double
    double d = r.nextDouble();
    aos.writeDouble(d);
    dos.writeDouble(d);

    // strings
    String str = RandomStringUtils.random(20);
    aos.writeBytes(str);
    aos.writeChars(str);
    aos.writeUTF(str);
    dos.writeBytes(str);
    dos.writeChars(str);
    dos.writeUTF(str);

    byte[] expected = bos.toByteArray();
    assertEquals(expected.length, aos.size());

    byte[] actual = new byte[aos.size()];
    System.arraycopy(aos.getBytes(), 0, actual, 0, actual.length);
    // serialized bytes should be the same
    assertTrue(Arrays.equals(expected, actual));
}

From source file:darks.learning.word2vec.Word2Vec.java

/**
 * Save model//from   w  w  w.j  a va  2  s .  c o m
 * 
 * @param file Model file saved
 */
public void saveModel(File file) {
    log.info("Saving word2vec model to " + file);
    DataOutputStream dos = null;
    try {
        dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
        dos.writeInt(wordNodes.size());
        dos.writeInt(config.featureSize);
        double[] syn0 = null;
        for (Entry<String, WordNode> element : wordNodes.entrySet()) {
            byte[] bytes = element.getKey().getBytes();
            dos.writeInt(bytes.length);
            dos.write(bytes);
            syn0 = (element.getValue()).feature.toArray();
            for (int i = 0; i < config.featureSize; i++) {
                dos.writeDouble(syn0[i]);
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        IOUtils.closeStream(dos);
    }
}

From source file:MersenneTwisterFast.java

/** Writes the entire state of the MersenneTwister RNG to the stream
 *  @param stream output stream// www  .j a  va2 s.  c o  m
 *  @throws IOException exception from stream reading
 */
public void writeState(DataOutputStream stream) throws IOException {
    int len = mt.length;
    for (int x = 0; x < len; x++)
        stream.writeInt(mt[x]);

    len = mag01.length;
    for (int x = 0; x < len; x++)
        stream.writeInt(mag01[x]);

    stream.writeInt(mti);
    stream.writeDouble(__nextNextGaussian);
    stream.writeBoolean(__haveNextNextGaussian);
}

From source file:ml.shifu.shifu.core.dtrain.dt.BinaryDTSerializer.java

public static void save(ModelConfig modelConfig, List<ColumnConfig> columnConfigList,
        List<List<TreeNode>> baggingTrees, String loss, int inputCount, OutputStream output)
        throws IOException {
    DataOutputStream fos = null;

    try {/*  www.  j a  va  2  s  . c  o  m*/
        fos = new DataOutputStream(new GZIPOutputStream(output));
        // version
        fos.writeInt(CommonConstants.TREE_FORMAT_VERSION);
        fos.writeUTF(modelConfig.getAlgorithm());
        fos.writeUTF(loss);
        fos.writeBoolean(modelConfig.isClassification());
        fos.writeBoolean(modelConfig.getTrain().isOneVsAll());
        fos.writeInt(inputCount);

        Map<Integer, String> columnIndexNameMapping = new HashMap<Integer, String>();
        Map<Integer, List<String>> columnIndexCategoricalListMapping = new HashMap<Integer, List<String>>();
        Map<Integer, Double> numericalMeanMapping = new HashMap<Integer, Double>();
        for (ColumnConfig columnConfig : columnConfigList) {
            if (columnConfig.isFinalSelect()) {
                columnIndexNameMapping.put(columnConfig.getColumnNum(), columnConfig.getColumnName());
            }
            if (columnConfig.isCategorical() && CollectionUtils.isNotEmpty(columnConfig.getBinCategory())) {
                columnIndexCategoricalListMapping.put(columnConfig.getColumnNum(),
                        columnConfig.getBinCategory());
            }

            if (columnConfig.isNumerical() && columnConfig.getMean() != null) {
                numericalMeanMapping.put(columnConfig.getColumnNum(), columnConfig.getMean());
            }
        }

        if (columnIndexNameMapping.size() == 0) {
            boolean hasCandidates = CommonUtils.hasCandidateColumns(columnConfigList);
            for (ColumnConfig columnConfig : columnConfigList) {
                if (CommonUtils.isGoodCandidate(columnConfig, hasCandidates)) {
                    columnIndexNameMapping.put(columnConfig.getColumnNum(), columnConfig.getColumnName());
                }
            }
        }

        // serialize numericalMeanMapping
        fos.writeInt(numericalMeanMapping.size());
        for (Entry<Integer, Double> entry : numericalMeanMapping.entrySet()) {
            fos.writeInt(entry.getKey());
            // for some feature, it is null mean value, it is not selected, just set to 0d to avoid NPE
            fos.writeDouble(entry.getValue() == null ? 0d : entry.getValue());
        }
        // serialize columnIndexNameMapping
        fos.writeInt(columnIndexNameMapping.size());
        for (Entry<Integer, String> entry : columnIndexNameMapping.entrySet()) {
            fos.writeInt(entry.getKey());
            fos.writeUTF(entry.getValue());
        }
        // serialize columnIndexCategoricalListMapping
        fos.writeInt(columnIndexCategoricalListMapping.size());
        for (Entry<Integer, List<String>> entry : columnIndexCategoricalListMapping.entrySet()) {
            List<String> categories = entry.getValue();
            if (categories != null) {
                fos.writeInt(entry.getKey());
                fos.writeInt(categories.size());
                for (String category : categories) {
                    // There is 16k limitation when using writeUTF() function.
                    // if the category value is larger than 10k, write a marker -1 and write bytes instead of
                    // writeUTF;
                    // in read part logic should be changed also to readByte not readUTF according to the marker
                    if (category.length() < Constants.MAX_CATEGORICAL_VAL_LEN) {
                        fos.writeUTF(category);
                    } else {
                        fos.writeShort(UTF_BYTES_MARKER); // marker here
                        byte[] bytes = category.getBytes("UTF-8");
                        fos.writeInt(bytes.length);
                        for (int i = 0; i < bytes.length; i++) {
                            fos.writeByte(bytes[i]);
                        }
                    }
                }
            }
        }

        Map<Integer, Integer> columnMapping = getColumnMapping(columnConfigList);
        fos.writeInt(columnMapping.size());
        for (Entry<Integer, Integer> entry : columnMapping.entrySet()) {
            fos.writeInt(entry.getKey());
            fos.writeInt(entry.getValue());
        }

        // after model version 4 (>=4), IndependentTreeModel support bagging, here write a default RF/GBT size 1
        fos.writeInt(baggingTrees.size());
        for (int i = 0; i < baggingTrees.size(); i++) {
            List<TreeNode> trees = baggingTrees.get(i);
            int treeLength = trees.size();
            fos.writeInt(treeLength);
            for (TreeNode treeNode : trees) {
                treeNode.write(fos);
            }
        }
    } catch (IOException e) {
        LOG.error("Error in writing output.", e);
    } finally {
        IOUtils.closeStream(fos);
    }
}

From source file:org.nd4j.linalg.util.ArrayUtil.java

public static void write(double[] data, DataOutputStream dos) throws IOException {
    for (int i = 0; i < data.length; i++)
        dos.writeDouble(data[i]);
}

From source file:org.apache.jmeter.protocol.mqttws.client.MqttPublisher.java

public byte[] createPayload(String message, String useTimeStamp, String useNumSeq, String type_value,
        String format, String charset) throws IOException, NumberFormatException {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    DataOutputStream d = new DataOutputStream(b);
    // flags     
    byte flags = 0x00;
    if ("TRUE".equals(useTimeStamp))
        flags |= 0x80;/* w  ww.  j  a v a  2  s.c  om*/
    if ("TRUE".equals(useNumSeq))
        flags |= 0x40;
    if (MQTTPublisherGui.INT.equals(type_value))
        flags |= 0x20;
    if (MQTTPublisherGui.LONG.equals(type_value))
        flags |= 0x10;
    if (MQTTPublisherGui.FLOAT.equals(type_value))
        flags |= 0x08;
    if (MQTTPublisherGui.DOUBLE.equals(type_value))
        flags |= 0x04;
    if (MQTTPublisherGui.STRING.equals(type_value))
        flags |= 0x02;
    if (!"TEXT".equals(type_value)) {
        d.writeByte(flags);
    }
    // TimeStamp
    if ("TRUE".equals(useTimeStamp)) {
        Date date = new java.util.Date();
        d.writeLong(date.getTime());
    }
    // Number Sequence
    if ("TRUE".equals(useNumSeq)) {
        d.writeInt(numSeq++);

    }
    // Value            
    if (MQTTPublisherGui.INT.equals(type_value)) {
        d.writeInt(Integer.parseInt(message));
    } else if (MQTTPublisherGui.LONG.equals(type_value)) {
        d.writeLong(Long.parseLong(message));
    } else if (MQTTPublisherGui.DOUBLE.equals(type_value)) {
        d.writeDouble(Double.parseDouble(message));
    } else if (MQTTPublisherGui.FLOAT.equals(type_value)) {
        d.writeDouble(Float.parseFloat(message));
    } else if (MQTTPublisherGui.STRING.equals(type_value)) {
        d.write(message.getBytes());
    } else if ("TEXT".equals(type_value)) {
        d.write(message.getBytes());
    } else if ("TEXT_POOL".equals(type_value)) {
        String random_message = createRandomMessageFromPool(message);
        d.write(random_message.getBytes());
    }

    // Format: Encoding        
    if (MQTTPublisherGui.BINARY.equals(format)) {
        BinaryCodec encoder = new BinaryCodec();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.BASE64.equals(format)) {
        return Base64.encodeBase64(b.toByteArray());
    } else if (MQTTPublisherGui.BINHEX.equals(format)) {
        Hex encoder = new Hex();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.PLAIN_TEXT.equals(format)) {
        String s = new String(b.toByteArray(), charset);
        return s.getBytes();

    } else
        return b.toByteArray();
}

From source file:org.apache.jmeter.protocol.mqtt.client.MqttPublisher.java

public byte[] createPayload(String message, String useTimeStamp, String useNumSeq, String type_value,
        String format, String charset) throws IOException, NumberFormatException {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    DataOutputStream d = new DataOutputStream(b);
    // flags     
    byte flags = 0x00;
    if ("TRUE".equals(useTimeStamp))
        flags |= 0x80;//ww w .j  a va2  s .co m
    if ("TRUE".equals(useNumSeq))
        flags |= 0x40;
    if (MQTTPublisherGui.INT.equals(type_value))
        flags |= 0x20;
    if (MQTTPublisherGui.LONG.equals(type_value))
        flags |= 0x10;
    if (MQTTPublisherGui.FLOAT.equals(type_value))
        flags |= 0x08;
    if (MQTTPublisherGui.DOUBLE.equals(type_value))
        flags |= 0x04;
    if (MQTTPublisherGui.STRING.equals(type_value))
        flags |= 0x02;
    if (!"TEXT".equals(type_value)) {
        d.writeByte(flags);
    }
    // TimeStamp
    if ("TRUE".equals(useTimeStamp)) {
        Date date = new java.util.Date();
        d.writeLong(date.getTime());
    }
    // Number Sequence
    if ("TRUE".equals(useNumSeq)) {
        d.writeInt(numSeq++);

    }
    // Value            
    if (MQTTPublisherGui.INT.equals(type_value)) {
        d.writeInt(Integer.parseInt(message));
    } else if (MQTTPublisherGui.LONG.equals(type_value)) {
        d.writeLong(Long.parseLong(message));
    } else if (MQTTPublisherGui.DOUBLE.equals(type_value)) {
        d.writeDouble(Double.parseDouble(message));
    } else if (MQTTPublisherGui.FLOAT.equals(type_value)) {
        d.writeDouble(Float.parseFloat(message));
    } else if (MQTTPublisherGui.STRING.equals(type_value)) {
        d.write(message.getBytes());
    } else if ("TEXT".equals(type_value)) {
        d.write(message.getBytes());
    }

    // Format: Encoding        
    if (MQTTPublisherGui.BINARY.equals(format)) {
        BinaryCodec encoder = new BinaryCodec();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.BASE64.equals(format)) {
        return Base64.encodeBase64(b.toByteArray());
    } else if (MQTTPublisherGui.BINHEX.equals(format)) {
        Hex encoder = new Hex();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.PLAIN_TEXT.equals(format)) {
        String s = new String(b.toByteArray(), charset);
        return s.getBytes();

    } else
        return b.toByteArray();
}

From source file:ClassFile.java

public void write(DataOutputStream dos, ConstantPoolInfo pool[]) throws IOException, Exception {
    dos.write(type);//from ww w  .  j ava2 s  .  com
    switch (type) {
    case CLASS:
    case STRING:
        dos.writeShort(indexOf(arg1, pool));
        break;
    case FIELDREF:
    case METHODREF:
    case INTERFACE:
    case NAMEANDTYPE:
        dos.writeShort(indexOf(arg1, pool));
        dos.writeShort(indexOf(arg2, pool));
        break;
    case INTEGER:
        dos.writeInt(intValue);
        break;
    case FLOAT:
        dos.writeFloat(floatValue);
        break;
    case LONG:
        dos.writeLong(longValue);
        break;
    case DOUBLE:
        dos.writeDouble(doubleValue);
        break;
    case ASCIZ:
    case UNICODE:
        dos.writeShort(strValue.length());
        dos.writeBytes(strValue);
        break;
    default:
        throw new Exception("ConstantPoolInfo::write() - bad type.");
    }
}