Example usage for java.io DataOutputStream writeFloat

List of usage examples for java.io DataOutputStream writeFloat

Introduction

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

Prototype

public final void writeFloat(float v) throws IOException 

Source Link

Document

Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream as a 4-byte quantity, high byte first.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    FileOutputStream fos = new FileOutputStream("C:/WriteFloat.txt");
    DataOutputStream dos = new DataOutputStream(fos);

    float f = 5.314f;
    dos.writeFloat(f);
    dos.close();/*from ww w.java2  s  .  c o m*/
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    ServerSocket ssock = new ServerSocket(1234);
    while (true) {
        System.out.println("Listening");
        Socket sock = ssock.accept();

        DataOutputStream dstream = new DataOutputStream(sock.getOutputStream());
        dstream.writeFloat(3.14159265f);
        dstream.close();/* w  w  w  .jav  a2  s  .co m*/
        sock.close();
    }
}

From source file:Main.java

public static void main(String[] args) throws IOException {
    float[] fbuf = { 12.34f, 23.34f, 45.56f, 67.78f, 12.55f, 77.88f };

    FileOutputStream fos = new FileOutputStream("c:\\test.txt");
    DataOutputStream dos = new DataOutputStream(fos);
    for (float f : fbuf) {
        dos.writeFloat(f);
    }//  w  ww  .  j av a  2s. com
    dos.flush();
    InputStream is = new FileInputStream("c:\\test.txt");
    DataInputStream dis = new DataInputStream(is);

    while (dis.available() > 0) {
        float c = dis.readFloat();
        System.out.print(c);
    }
}

From source file:Main.java

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

    float[] fbuf = { 123.345f, 234.567f, 123.123f, 123.123f, 123.123f, 123.345f };

    FileOutputStream fos = new FileOutputStream("c:\\test.txt");
    DataOutputStream dos = new DataOutputStream(fos);

    for (float f : fbuf) {
        dos.writeFloat(f);
    }/*from w ww .j a v  a2s.  c  o  m*/

    dos.flush();

    InputStream is = new FileInputStream("c:\\test.txt");

    DataInputStream dis = new DataInputStream(is);

    while (dis.available() > 0) {
        float c = dis.readFloat();
        System.out.print(c + " ");
    }
}

From source file:MainClass.java

public static void main(String args[]) {
    try {//from  w  w  w  .  j  av  a2 s.  com

        FileOutputStream fos = new FileOutputStream(args[0]);

        DataOutputStream dos = new DataOutputStream(fos);

        dos.writeBoolean(false);
        dos.writeByte(Byte.MAX_VALUE);
        dos.writeChar('A');
        dos.writeDouble(Double.MAX_VALUE);
        dos.writeFloat(Float.MAX_VALUE);
        dos.writeInt(Integer.MAX_VALUE);
        dos.writeLong(Long.MAX_VALUE);
        dos.writeShort(Short.MAX_VALUE);

        fos.close();
    } catch (Exception e) {
        System.out.println("Exception: " + e);
    }
}

From source file:it.unimi.dsi.webgraph.algo.HyperBall.java

public static void main(String arg[])
        throws IOException, JSAPException, IllegalArgumentException, ClassNotFoundException,
        IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
    SimpleJSAP jsap = new SimpleJSAP(HyperBall.class.getName(),
            "Runs HyperBall on the given graph, possibly computing positive geometric centralities.\n\nPlease note that to compute negative centralities on directed graphs (which is usually what you want) you have to compute positive centralities on the transpose.",
            new Parameter[] {
                    new FlaggedOption("log2m", JSAP.INTEGER_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'l',
                            "log2m", "The logarithm of the number of registers."),
                    new FlaggedOption("upperBound", JSAP.LONGSIZE_PARSER, Long.toString(Long.MAX_VALUE),
                            JSAP.NOT_REQUIRED, 'u', "upper-bound",
                            "An upper bound to the number of iterations."),
                    new FlaggedOption("threshold", JSAP.DOUBLE_PARSER, "-1", JSAP.NOT_REQUIRED, 't',
                            "threshold",
                            "A threshold that will be used to stop the computation by relative increment. If it is -1, the iteration will stop only when all registers do not change their value (recommended)."),
                    new FlaggedOption("threads", JSAP.INTSIZE_PARSER, "0", JSAP.NOT_REQUIRED, 'T', "threads",
                            "The number of threads to be used. If 0, the number will be estimated automatically."),
                    new FlaggedOption("granularity", JSAP.INTSIZE_PARSER, Integer.toString(DEFAULT_GRANULARITY),
                            JSAP.NOT_REQUIRED, 'g', "granularity",
                            "The number of node per task in a multicore environment."),
                    new FlaggedOption("bufferSize", JSAP.INTSIZE_PARSER,
                            Util.formatBinarySize(DEFAULT_BUFFER_SIZE), JSAP.NOT_REQUIRED, 'b', "buffer-size",
                            "The size of an I/O buffer in bytes."),
                    new FlaggedOption("neighbourhoodFunction", JSAP.STRING_PARSER, JSAP.NO_DEFAULT,
                            JSAP.NOT_REQUIRED, 'n', "neighbourhood-function",
                            "Store an approximation the neighbourhood function in text format."),
                    new FlaggedOption("sumOfDistances", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            'd', "sum-of-distances",
                            "Store an approximation of the sum of distances from each node as a binary list of floats."),
                    new FlaggedOption("harmonicCentrality", JSAP.STRING_PARSER, JSAP.NO_DEFAULT,
                            JSAP.NOT_REQUIRED, 'h', "harmonic-centrality",
                            "Store an approximation of the positive harmonic centrality (the sum of the reciprocals of distances from each node) as a binary list of floats."),
                    new FlaggedOption("discountedGainCentrality", JSAP.STRING_PARSER, JSAP.NO_DEFAULT,
                            JSAP.NOT_REQUIRED, 'z', "discounted-gain-centrality",
                            "A positive discounted gain centrality to be approximated and stored; it is specified as O:F where O is the spec of an object of type Int2DoubleFunction and F is the name of the file where the binary list of floats will be stored. The spec can be either the name of a public field of HyperBall, or a constructor invocation of a class implementing Int2DoubleFunction.")
                                    .setAllowMultipleDeclarations(true),
                    new FlaggedOption("closenessCentrality", JSAP.STRING_PARSER, JSAP.NO_DEFAULT,
                            JSAP.NOT_REQUIRED, 'c', "closeness-centrality",
                            "Store an approximation of the positive closeness centrality of each node (the reciprocal of sum of the distances from each node) as a binary list of floats. Terminal nodes will have centrality equal to zero."),
                    new FlaggedOption("linCentrality", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            'L', "lin-centrality",
                            "Store an approximation of the positive Lin centrality of each node (the reciprocal of sum of the distances from each node multiplied by the square of the number of nodes reachable from the node) as a binary list of floats. Terminal nodes will have centrality equal to one."),
                    new FlaggedOption("nieminenCentrality", JSAP.STRING_PARSER, JSAP.NO_DEFAULT,
                            JSAP.NOT_REQUIRED, 'N', "nieminen-centrality",
                            "Store an approximation of the positive Nieminen centrality of each node (the square of the number of nodes reachable from each node minus the sum of the distances from the node) as a binary list of floats."),
                    new FlaggedOption("reachable", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'r',
                            "reachable",
                            "Store an approximation of the number of nodes reachable from each node as a binary list of floats."),
                    new FlaggedOption("seed", JSAP.LONG_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'S', "seed",
                            "The random seed."),
                    new Switch("spec", 's', "spec",
                            "The basename is not a basename but rather a specification of the form <ImmutableGraphImplementation>(arg,arg,...)."),
                    new Switch("offline", 'o', "offline",
                            "Do not load the graph in main memory. If this option is used, the graph will be loaded in offline (for one thread) or mapped (for several threads) mode."),
                    new Switch("external", 'e', "external",
                            "Use an external dump file instead of core memory to store new counter values. Note that the file might be very large: you might need to set suitably the Java temporary directory (-Djava.io.tmpdir=DIR)."),
                    new UnflaggedOption("basename", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED,
                            JSAP.NOT_GREEDY, "The basename of the graph."),
                    new UnflaggedOption("basenamet", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            JSAP.NOT_GREEDY,
                            "The basename of the transpose graph for systolic computations (strongly suggested). If it is equal to <basename>, the graph will be assumed to be symmetric and will be loaded just once."), });

    JSAPResult jsapResult = jsap.parse(arg);
    if (jsap.messagePrinted())
        System.exit(1);// w  w  w  . j  a  va  2 s . com

    final boolean spec = jsapResult.getBoolean("spec");
    final boolean external = jsapResult.getBoolean("external");
    final boolean offline = jsapResult.getBoolean("offline");
    final String neighbourhoodFunctionFile = jsapResult.getString("neighbourhoodFunction");
    final boolean neighbourhoodFunction = jsapResult.userSpecified("neighbourhoodFunction");
    final String sumOfDistancesFile = jsapResult.getString("sumOfDistances");
    final boolean sumOfDistances = jsapResult.userSpecified("sumOfDistances");
    final String harmonicCentralityFile = jsapResult.getString("harmonicCentrality");
    final boolean harmonicCentrality = jsapResult.userSpecified("harmonicCentrality");
    final String closenessCentralityFile = jsapResult.getString("closenessCentrality");
    final boolean closenessCentrality = jsapResult.userSpecified("closenessCentrality");
    final String linCentralityFile = jsapResult.getString("linCentrality");
    final boolean linCentrality = jsapResult.userSpecified("linCentrality");
    final String nieminenCentralityFile = jsapResult.getString("nieminenCentrality");
    final boolean nieminenCentrality = jsapResult.userSpecified("nieminenCentrality");
    final String reachableFile = jsapResult.getString("reachable");
    final boolean reachable = jsapResult.userSpecified("reachable");
    final String basename = jsapResult.getString("basename");
    final String basenamet = jsapResult.getString("basenamet");
    final ProgressLogger pl = new ProgressLogger(LOGGER);
    final int log2m = jsapResult.getInt("log2m");
    final int threads = jsapResult.getInt("threads");
    final int bufferSize = jsapResult.getInt("bufferSize");
    final int granularity = jsapResult.getInt("granularity");
    final long seed = jsapResult.userSpecified("seed") ? jsapResult.getLong("seed") : Util.randomSeed();

    final String[] discountedGainCentralitySpec = jsapResult.getStringArray("discountedGainCentrality");
    final Int2DoubleFunction[] discountFunction = new Int2DoubleFunction[discountedGainCentralitySpec.length];
    final String[] discountedGainCentralityFile = new String[discountedGainCentralitySpec.length];
    for (int i = 0; i < discountedGainCentralitySpec.length; i++) {
        int pos = discountedGainCentralitySpec[i].indexOf(':');
        if (pos < 0)
            throw new IllegalArgumentException("Wrong spec <" + discountedGainCentralitySpec[i] + ">");
        discountedGainCentralityFile[i] = discountedGainCentralitySpec[i].substring(pos + 1);
        String gainSpec = discountedGainCentralitySpec[i].substring(0, pos);
        Int2DoubleFunction candidateFunction;
        try {
            candidateFunction = (Int2DoubleFunction) HyperBall.class.getField(gainSpec).get(null);
        } catch (SecurityException e) {
            throw new IllegalArgumentException("Field " + gainSpec + " exists but cannot be accessed", e);
        } catch (ClassCastException e) {
            throw new IllegalArgumentException(
                    "Field " + gainSpec + " exists but it is not of type Int2DoubleFunction", e);
        } catch (NoSuchFieldException e) {
            candidateFunction = null;
        }
        discountFunction[i] = candidateFunction == null
                ? ObjectParser.fromSpec(gainSpec, Int2DoubleFunction.class)
                : candidateFunction;
    }

    final ImmutableGraph graph = spec
            ? ObjectParser.fromSpec(basename, ImmutableGraph.class, GraphClassParser.PACKAGE)
            : offline
                    ? ((numberOfThreads(threads) == 1 && basenamet == null
                            ? ImmutableGraph.loadOffline(basename)
                            : ImmutableGraph.loadMapped(basename, new ProgressLogger())))
                    : ImmutableGraph.load(basename, new ProgressLogger());

    final ImmutableGraph grapht = basenamet == null ? null
            : basenamet.equals(basename) ? graph
                    : spec ? ObjectParser.fromSpec(basenamet, ImmutableGraph.class, GraphClassParser.PACKAGE)
                            : offline ? ImmutableGraph.loadMapped(basenamet, new ProgressLogger())
                                    : ImmutableGraph.load(basenamet, new ProgressLogger());

    final HyperBall hyperBall = new HyperBall(graph, grapht, log2m, pl, threads, bufferSize, granularity,
            external, sumOfDistances || closenessCentrality || linCentrality || nieminenCentrality,
            harmonicCentrality, discountFunction, seed);
    hyperBall.run(jsapResult.getLong("upperBound"), jsapResult.getDouble("threshold"));
    hyperBall.close();

    if (neighbourhoodFunction) {
        final PrintStream stream = new PrintStream(
                new FastBufferedOutputStream(new FileOutputStream(neighbourhoodFunctionFile)));
        for (DoubleIterator i = hyperBall.neighbourhoodFunction.iterator(); i.hasNext();)
            stream.println(BigDecimal.valueOf(i.nextDouble()).toPlainString());
        stream.close();
    }

    if (sumOfDistances)
        BinIO.storeFloats(hyperBall.sumOfDistances, sumOfDistancesFile);
    if (harmonicCentrality)
        BinIO.storeFloats(hyperBall.sumOfInverseDistances, harmonicCentralityFile);
    for (int i = 0; i < discountedGainCentralitySpec.length; i++)
        BinIO.storeFloats(hyperBall.discountedCentrality[i], discountedGainCentralityFile[i]);
    if (closenessCentrality) {
        final int n = graph.numNodes();
        final DataOutputStream dos = new DataOutputStream(
                new FastBufferedOutputStream(new FileOutputStream(closenessCentralityFile)));
        for (int i = 0; i < n; i++)
            dos.writeFloat(hyperBall.sumOfDistances[i] == 0 ? 0 : 1 / hyperBall.sumOfDistances[i]);
        dos.close();
    }
    if (linCentrality) {
        final int n = graph.numNodes();
        final DataOutputStream dos = new DataOutputStream(
                new FastBufferedOutputStream(new FileOutputStream(linCentralityFile)));
        for (int i = 0; i < n; i++) {
            // Lin's index for isolated nodes is by (our) definition one (it's smaller than any other node).
            if (hyperBall.sumOfDistances[i] == 0)
                dos.writeFloat(1);
            else {
                final double count = hyperBall.count(i);
                dos.writeFloat((float) (count * count / hyperBall.sumOfDistances[i]));
            }
        }
        dos.close();
    }
    if (nieminenCentrality) {
        final int n = graph.numNodes();
        final DataOutputStream dos = new DataOutputStream(
                new FastBufferedOutputStream(new FileOutputStream(nieminenCentralityFile)));
        for (int i = 0; i < n; i++) {
            final double count = hyperBall.count(i);
            dos.writeFloat((float) (count * count - hyperBall.sumOfDistances[i]));
        }
        dos.close();
    }
    if (reachable) {
        final int n = graph.numNodes();
        final DataOutputStream dos = new DataOutputStream(
                new FastBufferedOutputStream(new FileOutputStream(reachableFile)));
        for (int i = 0; i < n; i++)
            dos.writeFloat((float) hyperBall.count(i));
        dos.close();
    }
}

From source file:Main.java

public static byte[] convertToB64(float[] a) {
    ByteArrayOutputStream os = new ByteArrayOutputStream(a.length * 4 + 2);
    DataOutputStream dou = new DataOutputStream(os);
    try {//from w  w w  .jav  a  2s.  co m
        for (int i = 0; i < a.length; i++)
            dou.writeFloat(a[i]);
        return encode(os.toByteArray());
    } catch (Exception s) {
        return null;
    }
}

From source file:Main.java

public static void writeFloats(String file, float[] floats) throws IOException {
    DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file), 4 * 1024));
    try {//ww w .ja  va 2 s.  c om
        int len = floats.length;
        out.writeInt(len);
        for (int i = 0; i < len; i++) {
            out.writeFloat(floats[i]);
        }
    } finally {
        out.close();
    }
}

From source file:Main.java

public static void writeSettings(String file, Object... objs) throws IOException {
    DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file), 1024));
    try {//from   ww w .j  a  va2  s .co  m
        out.writeInt(objs.length);
        for (Object obj : objs) {
            char cl;
            if (obj instanceof Byte) {
                cl = 'Y';
            } else {
                cl = obj.getClass().getSimpleName().charAt(0);
            }

            out.writeChar(cl);
            if (obj instanceof String) {
                out.writeUTF((String) obj);
            } else if (obj instanceof Float) {
                out.writeFloat((Float) obj);
            } else if (obj instanceof Double) {
                out.writeDouble((Double) obj);
            } else if (obj instanceof Integer) {
                out.writeInt((Integer) obj);
            } else if (obj instanceof Long) {
                out.writeLong((Long) obj);
            } else if (obj instanceof Boolean) {
                out.writeBoolean((Boolean) obj);
            } else {
                throw new IllegalStateException("Unsupported type");
            }
        }
    } finally {
        out.close();
    }
}

From source file:net.datenwerke.transloader.primitive.WrapperConverter.java

private static void write(Object wrapper, DataOutputStream dataStream) throws IOException {
    char typeCode = getTypeCode(wrapper);
    switch (typeCode) {
    case 'B':
        dataStream.writeByte(intValue(wrapper));
        break;//w  w  w .j a v a 2s  .co m
    case 'C':
        dataStream.writeChar(charValue(wrapper));
        break;
    case 'S':
        dataStream.writeShort(intValue(wrapper));
        break;
    case 'I':
        dataStream.writeInt(intValue(wrapper));
        break;
    case 'J':
        dataStream.writeLong(number(wrapper).longValue());
        break;
    case 'F':
        dataStream.writeFloat(number(wrapper).floatValue());
        break;
    case 'D':
        dataStream.writeDouble(number(wrapper).doubleValue());
        break;
    case 'Z':
        dataStream.writeBoolean(booleanValue(wrapper));
    }
}