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

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

    // write the data out
    DataOutputStream out = new DataOutputStream(new FileOutputStream("invoice1.txt"));

    double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
    int[] units = { 12, 8, 13, 29, 50 };
    String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" };

    for (int i = 0; i < prices.length; i++) {
        out.writeDouble(prices[i]);//from   w  w w  .  j  av  a  2 s  .  co  m
        out.writeChar('\t');
        out.writeInt(units[i]);
        out.writeChar('\t');
        out.writeChars(descs[i]);
        out.writeChar('\n');
    }
    out.close();

    // read it in again
    DataInputStream in = new DataInputStream(new FileInputStream("invoice1.txt"));

    double price;
    int unit;
    StringBuffer desc;
    double total = 0.0;

    try {
        while (true) {
            price = in.readDouble();
            in.readChar(); // throws out the tab
            unit = in.readInt();
            in.readChar(); // throws out the tab
            char chr;
            desc = new StringBuffer(20);
            char lineSep = System.getProperty("line.separator").charAt(0);
            while ((chr = in.readChar()) != lineSep)
                desc.append(chr);
            System.out.println("You've ordered " + unit + " units of " + desc + " at $" + price);
            total = total + unit * price;
        }
    } catch (EOFException e) {
    }
    System.out.println("For a TOTAL of: $" + total);
    in.close();
}

From source file:org.schreibubi.JCombinationsTools.coordinator.Coordinator.java

/**
 * @param args//  w  ww. ja va2 s .co  m
 */
public static void main(String[] args) {

    Info.printVersion("Coordinator");
    try {

        CoordinatorOptions[] settings = CoordinatorOptions.values();
        SettingsSingleton.initialize("Coordinator", settings);
        // command line arguments have the highest priority, so they go into level 2
        SettingsSingleton.getInstance().parseArguments(args, 2);

        if (SettingsSingleton.getInstance().getProperty("help").equals("true")) {
            SettingsSingleton.getInstance().displayHelp();
            Runtime.getRuntime().exit(0);
        }

        if (SettingsSingleton.getInstance().getProperty("version").equals("true")) {
            Info.printVersion("SetiPrinter");
            Runtime.getRuntime().exit(0);
        }

        String combinationFileName = SettingsSingleton.getInstance().getProperty("combinations");

        // pre-tags
        VArrayList<String> preTags = new VArrayList<String>();
        String preTagsString = SettingsSingleton.getInstance().getProperty("pretags");
        preTags = new VArrayList<String>(Arrays.asList(preTagsString.split(",")));
        // post-tags
        VArrayList<String> postTags = new VArrayList<String>();
        String postTagsString = SettingsSingleton.getInstance().getProperty("posttags");
        postTags = new VArrayList<String>(Arrays.asList(postTagsString.split(",")));

        FileNameLookupSingleton.initialize(preTags, postTags);

        File dir = new File(combinationFileName).getAbsoluteFile().getParentFile();
        File combinationFile = FileNameLookupSingleton.getInstance().lookup(dir, combinationFileName);
        System.out.println("Processing: " + combinationFile.getName());

        // Generate all possible combinations
        System.out.print("Generating and evaluation all combinations...");
        VHashMap<String> optionsFromEvalGenWalker = new VHashMap<String>();
        VArrayList<VHashMap<Symbol>> symbolTableLines = EvalGenCombinations
                .exec(new FileReader(combinationFile), dir, optionsFromEvalGenWalker);
        System.out.println("done");

        // now additional default options are known...
        // -----------------------------------------------------------------------------
        String argumentsString = optionsFromEvalGenWalker.get("Coordinator");
        if (argumentsString != null) {
            String[] arguments = argumentsString.split(" ");
            SettingsSingleton.getInstance().parseArguments(arguments, 1);
        }

        if (SettingsSingleton.getInstance().areRequiredOptionsSet() == false) {
            SettingsSingleton.getInstance().displayHelp();
            Runtime.getRuntime().exit(0);
        }

        String conditionFilePrefix = SettingsSingleton.getInstance().getProperty("conditionprefix");

        boolean ignoreMissingCBMpos = false;
        if (SettingsSingleton.getInstance().getProperty("ignoremissingcbmpos").equals("true")) {
            ignoreMissingCBMpos = true;
        }
        boolean silent = false;
        if (SettingsSingleton.getInstance().getProperty("silent").equals("true")) {
            silent = true;
        }

        String cbmOutputDir = SettingsSingleton.getInstance().getProperty("cbmdir");
        String patternInputDir = SettingsSingleton.getInstance().getProperty("patterndir");
        String pcfOutputDir = SettingsSingleton.getInstance().getProperty("pcfdir");

        int cbmOffset = Integer.parseInt(SettingsSingleton.getInstance().getProperty("cbmOffset"));

        String conditionFileTemplateName = conditionFilePrefix + ".template";
        String conditionFileHeaderName = conditionFilePrefix + ".header";

        if (!SettingsSingleton.getInstance().getProperty("conditiontemplate").equals("")) {
            conditionFileTemplateName = SettingsSingleton.getInstance().getProperty("conditiontemplate");
        }
        if (!SettingsSingleton.getInstance().getProperty("conditionheader").equals("")) {
            conditionFileHeaderName = SettingsSingleton.getInstance().getProperty("conditionheader");
        }

        String conditionFileName = "";
        if (!SettingsSingleton.getInstance().getProperty("condition").equals("")) {
            conditionFileName = SettingsSingleton.getInstance().getProperty("condition");
        } else {
            int dotPos = combinationFileName.indexOf(".");
            if (dotPos > -1) {
                conditionFileName = conditionFilePrefix + "_" + combinationFileName.subSequence(0, dotPos);
            } else {
                conditionFileName = conditionFilePrefix + "_" + combinationFileName;
            }
        }
        String setiFile = SettingsSingleton.getInstance().getProperty("seti");
        // -----------------------------------------------------------------------------
        if (SettingsSingleton.getInstance().getProperty("nocbmgen").equals("false")) {
            boolean filesWereOverwritten = false;
            System.out.print("Creating CBM dat files...");

            SetiChainBuilder constructSetiChain = new SetiChainBuilder(setiFile);

            VHashMap<TemplateInfo> templateInfos = new VHashMap<TemplateInfo>();

            HashMap<String, Integer> patCbmSettings = new HashMap<String, Integer>();

            int cbmPatternCount = cbmOffset;

            for (ListIterator<VHashMap<Symbol>> i = symbolTableLines.listIterator(); i.hasNext();) {
                /* get variables used to fill out the actual template */
                VHashMap<Symbol> sT = i.next();

                String patName = sT.get("PATNAME").convertToString().getValue();
                TemplateInfo tI = templateInfos.get(patName);
                // if template was not done already before
                if (tI == null) {
                    // read in the cbm position file for this template
                    tI = readCBMpos(patternInputDir, patName, ignoreMissingCBMpos);
                    if (tI == null) {
                        if (!silent) {
                            System.err.println("WARNING: " + patName
                                    + ".asc does not contain a cbm part, but ignored due to manual override!");
                        }
                    } else {
                        templateInfos.put(patName, tI);
                    }
                }

                if (tI != null) {
                    // check if we already have a dat file with the same settings...
                    VArrayList<Symbol> currentSymbols = selectSymbols(sT, tI.getCbmNames());
                    currentSymbols.add(sT.get("PATNAME"));

                    Integer foundNumber = patCbmSettings.get(currentSymbols.toString());
                    if (foundNumber != null) {
                        // we have already a dat file containing the same settings
                        // so set the CBMNAME accordingly
                        sT.put("CBMNAME", new SymbolString(Integer.toHexString(foundNumber).toUpperCase()));
                    } else {
                        // first time we have these conditions
                        cbmPatternCount++;
                        String cbmName = Integer.toHexString(cbmPatternCount);

                        VArrayList<String> cbmNames = tI.getCbmNames();

                        // remember our settings...
                        VArrayList<Symbol> selectedSymbols = selectSymbols(sT, cbmNames);
                        selectedSymbols.add(sT.get("PATNAME"));
                        patCbmSettings.put(selectedSymbols.toString(), cbmPatternCount);

                        sT.put("CBMNAME", new SymbolString(cbmName.toUpperCase()));

                        // calculate seti-chains and put them in CBM chunks
                        for (CBMChunk chunk : tI.getCbms())
                            if (sT.get(chunk.getName()) != null) {
                                VArrayList<Integer> content = constructSetiChain.createCBMChain(
                                        sT.get(chunk.getName()).convertToString(), tI.getChannels(),
                                        chunk.getLength(), chunk.getSetiType());
                                chunk.setCbmContent(content);
                            }
                        // now optimize CBMChunks (are already in ascending
                        // order, so we only need to check the next one)
                        VArrayList<CBMChunk> compressedChunks = new VArrayList<CBMChunk>(tI.getCbms());

                        // write them to file

                        File cbmOutput = new File(cbmOutputDir, cbmName + ".dat");
                        if (cbmOutput.exists()) {
                            filesWereOverwritten = true;
                        }
                        DataOutputStream out = new DataOutputStream(
                                new BufferedOutputStream(new FileOutputStream(cbmOutput)));
                        out.writeInt(compressedChunks.size());
                        for (CBMChunk chunk : compressedChunks)
                            if (sT.get(chunk.getName()) != null) {
                                // output hexstring to cbm-file
                                out.writeInt(chunk.getStart());
                                out.writeInt(chunk.getLength());
                                for (Integer integer : chunk.getCbmContent()) {
                                    out.writeInt(integer);
                                }
                            } else
                                throw new Exception(chunk.getName() + " does not exist");

                        out.close();
                    }
                } else {
                    sT.put("CBMNAME", new SymbolString(""));
                }
            }
            System.out.println("done");
            if ((!silent) && (filesWereOverwritten)) {
                System.err.println("WARNING: Some .dat files were overwritten!");
            }
        } else {
            // Even if no CBM.dat generation is requested, we need to set the CBMNAME...
            for (ListIterator<VHashMap<Symbol>> i = symbolTableLines.listIterator(); i.hasNext();) {
                /* get variables used to fill out the actual template */
                VHashMap<Symbol> sT = i.next();
                sT.put("CBMNAME", new SymbolString(""));
            }
        }

        if (SettingsSingleton.getInstance().getProperty("nopcf").equals("false")) {
            // Create the condition file
            System.out.print("Creating " + conditionFileName + "...");
            TemplateEngine.exec(symbolTableLines, false, conditionFileName, false, conditionFileTemplateName,
                    new File("."), new File(pcfOutputDir), new File(conditionFileHeaderName), null);
            System.out.println("done");
        }

    } catch (ParseException e) {
    } catch (TokenStreamException e) {
        System.out.println("TokenStreamException: " + e.getMessage());
    } catch (RecognitionException e) {
        System.out.println("RecognitionException: " + e.getMessage());
    } catch (Exception e) {
        System.out.println("Coordinator error: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.splout.db.dnode.TCPStreamer.java

/**
 * This main method can be used for testing the TCP interface directly to a
 * local DNode. Will ask for protocol input from Stdin and print output to
 * Stdout/*from w  ww.  j  av a 2s .  c o  m*/
 */
public static void main(String[] args) throws UnknownHostException, IOException, SerializationException {
    SploutConfiguration config = SploutConfiguration.get();
    Socket clientSocket = new Socket("localhost", config.getInt(DNodeProperties.STREAMING_PORT));

    DataInputStream inFromServer = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
    DataOutputStream outToServer = new DataOutputStream(
            new BufferedOutputStream(clientSocket.getOutputStream()));

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter tablespace: ");
    String tablespace = reader.readLine();

    System.out.println("Enter version number: ");
    long versionNumber = Long.parseLong(reader.readLine());

    System.out.println("Enter partition: ");
    int partition = Integer.parseInt(reader.readLine());

    System.out.println("Enter query: ");
    String query = reader.readLine();

    outToServer.writeUTF(tablespace);
    outToServer.writeLong(versionNumber);
    outToServer.writeInt(partition);
    outToServer.writeUTF(query);

    outToServer.flush();

    byte[] buffer = new byte[0];
    boolean read;
    do {
        read = false;
        int nBytes = inFromServer.readInt();
        if (nBytes > 0) {
            buffer = new byte[nBytes];
            int inRead = inFromServer.read(buffer);
            if (inRead > 0) {
                Object[] res = ResultSerializer.deserialize(ByteBuffer.wrap(buffer), Object[].class);
                read = true;
                System.out.println(Arrays.toString(res));
            }
        }
    } while (read);

    clientSocket.close();
}

From source file:com.ebay.erl.mobius.core.model.Tuple.java

public static void main(String[] arg) throws Throwable {
    DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File("s:/test.binary")));
    //dos.writeUTF("00_DW_LSTG_ITEM");
    dos.writeInt(5);
    dos.flush();//from   w  ww  . ja  va 2 s.c o  m
    dos.close();
}

From source file:Main.java

public static void writeInt(DataOutputStream os, int i) throws IOException {
    os.writeInt(Integer.reverseBytes(i));
}

From source file:Main.java

public static byte[] convertIntToByteArray(int my_int) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    dos.writeInt(my_int);
    dos.close();/*w w w. j av  a2  s.  com*/
    byte[] int_bytes = bos.toByteArray();
    bos.close();
    return int_bytes;
}

From source file:WriteBinaryFile.java

private static void writeMovie(Product m, DataOutputStream out) throws Exception {
    out.writeUTF(m.title);/*  ww w  . j av  a 2s  . c o  m*/
    out.writeInt(m.year);
    out.writeDouble(m.price);
}

From source file:Main.java

public static byte[] intToByteArray(int number) {
    try {/* w  w w  . j a  v a2s. c om*/
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);
        dos.writeInt(number);
        dos.flush();
        // lenth have to be 2 byte
        byte[] d = bos.toByteArray();
        dos.close();

        return d;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jcodec.samples.mux.AVCMP4Mux.java

private static Buffer formPacket(NALUnit nu, InputStream nextNALUnit) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(baos);
    byte[] data = IOUtils.toByteArray(nextNALUnit);
    out.writeInt(data.length + 1);
    nu.write(out);/*  ww w  . j  av  a2s .co m*/
    out.write(data);
    return new Buffer(baos.toByteArray());
}

From source file:Main.java

public static void writeContatctInfo(String accountId, Vector contactInfo, File contactInfoFile)
        throws IOException {
    contactInfoFile.getParentFile().mkdirs();
    FileOutputStream contactFileOutputStream = new FileOutputStream(contactInfoFile);
    DataOutputStream out = new DataOutputStream(contactFileOutputStream);
    out.writeUTF((String) contactInfo.get(0));
    out.writeInt(((Integer) (contactInfo.get(1))).intValue());
    for (int i = 2; i < contactInfo.size(); ++i) {
        out.writeUTF((String) contactInfo.get(i));
    }//from   w  ww. j  a  v  a 2s .c om
    out.close();
}