Example usage for java.io DataInputStream close

List of usage examples for java.io DataInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:Util.PacketGenerator.java

public static void GenerateGraph() {
    try {/*  w  ww . jav a2  s.  c  o m*/
        for (int j = 6; j <= 6; j++) {
            File real = new File("D:\\Mestrado\\SketchMatrix\\trunk\\Simulations\\Analise\\Scenario1\\Topology"
                    + j + "\\Real.csv");
            for (int k = 1; k <= 4; k++) {
                File simu = new File(
                        "D:\\Mestrado\\SketchMatrix\\trunk\\Simulations\\Analise\\Scenario1\\Topology" + j
                                + "\\SimulacaoInstancia" + k + ".csv");

                FileInputStream simuFIS = new FileInputStream(simu);
                DataInputStream simuDIS = new DataInputStream(simuFIS);
                BufferedReader simuBR = new BufferedReader(new InputStreamReader(simuDIS));

                FileInputStream realFIS = new FileInputStream(real);
                DataInputStream realDIS = new DataInputStream(realFIS);
                BufferedReader realBR = new BufferedReader(new InputStreamReader(realDIS));

                String lineSimu = simuBR.readLine();
                String lineReal = realBR.readLine();

                XYSeries matrix = new XYSeries("Matriz", false, true);
                while (lineSimu != null && lineReal != null) {

                    lineSimu = lineSimu.replaceAll(",", ".");
                    String[] simuMatriz = lineSimu.split(";");
                    String[] realMatriz = lineReal.split(";");

                    for (int i = 0; i < simuMatriz.length; i++) {
                        try {
                            Integer valorReal = Integer.parseInt(realMatriz[i]);
                            Float valorSimu = Float.parseFloat(simuMatriz[i]);
                            matrix.add(valorReal.doubleValue() / 1000.0, valorSimu.doubleValue() / 1000.0);
                        } catch (NumberFormatException ex) {

                        }
                    }
                    lineSimu = simuBR.readLine();
                    lineReal = realBR.readLine();
                }

                simuFIS.close();
                simuDIS.close();
                simuBR.close();

                realFIS.close();
                realDIS.close();
                realBR.close();

                double maxPlot = Double.max(matrix.getMaxX(), matrix.getMaxY()) * 1.1;
                XYSeries middle = new XYSeries("Referncia");
                ;
                middle.add(0, 0);
                middle.add(maxPlot, maxPlot);
                XYSeries max = new XYSeries("Superior 20%");
                max.add(0, 0);
                max.add(maxPlot, maxPlot * 1.2);
                XYSeries min = new XYSeries("Inferior 20%");
                min.add(0, 0);
                min.add(maxPlot, maxPlot * 0.8);

                XYSeriesCollection dataset = new XYSeriesCollection();
                dataset.addSeries(middle);
                dataset.addSeries(matrix);
                dataset.addSeries(max);
                dataset.addSeries(min);
                JFreeChart chart;
                if (k == 4) {
                    chart = ChartFactory.createXYLineChart("Matriz de Trfego", "Real", "CMO-MT", dataset);
                } else {
                    chart = ChartFactory.createXYLineChart("Matriz de Trfego", "CMO-MT", "Zhao", dataset);
                }
                chart.setBackgroundPaint(Color.WHITE);
                chart.getPlot().setBackgroundPaint(Color.WHITE);
                chart.getTitle().setFont(new Font("Times New Roman", Font.BOLD, 13));

                chart.getLegend().setItemFont(new Font("Times New Roman", Font.TRUETYPE_FONT, 10));

                chart.getXYPlot().getDomainAxis().setLabelFont(new Font("Times New Roman", Font.BOLD, 10));
                chart.getXYPlot().getDomainAxis()
                        .setTickLabelFont(new Font("Times New Roman", Font.TRUETYPE_FONT, 1));
                chart.getXYPlot().getRangeAxis().setLabelFont(new Font("Times New Roman", Font.BOLD, 10));
                chart.getXYPlot().getRangeAxis()
                        .setTickLabelFont(new Font("Times New Roman", Font.TRUETYPE_FONT, 1));

                XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();

                renderer.setSeriesLinesVisible(1, false);
                renderer.setSeriesShapesVisible(1, true);

                renderer.setSeriesStroke(0, new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                        10.0f, new float[] { 0.1f }, 0.0f));
                renderer.setSeriesShape(1, new Ellipse2D.Float(-1.5f, -1.5f, 3f, 3f));
                renderer.setSeriesStroke(2, new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                        10.0f, new float[] { 3.0f }, 0.0f));
                renderer.setSeriesStroke(3, new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                        10.0f, new float[] { 3.0f }, 0.0f));

                renderer.setSeriesPaint(0, Color.BLACK);
                renderer.setSeriesPaint(1, Color.BLACK);
                renderer.setSeriesPaint(2, Color.BLACK);
                renderer.setSeriesPaint(3, Color.BLACK);

                int width = (int) (192 * 1.5f); /* Width of the image */

                int height = (int) (144 * 1.5f); /* Height of the image */

                File XYChart = new File(
                        "D:\\Mestrado\\SketchMatrix\\trunk\\Simulations\\Analise\\Scenario1\\Topology" + j
                                + "\\SimulacaoInstancia" + k + ".jpeg");
                ChartUtilities.saveChartAsJPEG(XYChart, chart, width, height);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:CoolBarExamples.java

private void setState(CoolBar coolBar, File file) throws IOException {
    if (!file.exists())
        throw new IOException("File does not exist: " + file);

    DataInputStream in = new DataInputStream(new FileInputStream(file));

    try {/*from www.j  av  a2  s . c om*/
        // Order
        int size = in.readInt();
        int[] order = new int[size];
        for (int i = 0; i < order.length; i++)
            order[i] = in.readInt();

        // Wrap indices.
        size = in.readInt();
        int[] wrapIndices = new int[size];
        for (int i = 0; i < wrapIndices.length; i++)
            wrapIndices[i] = in.readInt();

        // Sizes.
        size = in.readInt();
        Point[] sizes = new Point[size];
        for (int i = 0; i < sizes.length; i++)
            sizes[i] = new Point(in.readInt(), in.readInt());

        coolBar.setItemLayout(order, wrapIndices, sizes);
    } finally {
        in.close();
    }

}

From source file:com.drive.student.xutils.HttpUtils.java

/**
 * Server/*from  w ww  . j av a  2s .c  om*/
 *
 * @param urlStr
 *            ?
 * @param serverFileName
 *            ????? image.jpg
 * @param uploadFile
 *            ? /sdcard/a.jpg
 */
public void uploadFile(String urlStr, String serverFileName, File uploadFile) {
    try {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setChunkedStreamingMode(1024 * 1024);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", "multipart/form-data;file=" + uploadFile.getName());
        conn.setRequestProperty("filename", uploadFile.getName());
        OutputStream out = new DataOutputStream(conn.getOutputStream());
        DataInputStream in = new DataInputStream(new FileInputStream(uploadFile));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();
        out.flush();
        out.close();

        int response = conn.getResponseCode();

        if (response == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            LogUtil.e("hxk", "upload file success-->>");
        } else {
            LogUtil.e("hxk", "upload file fail-->> response = " + response);
        }
    } catch (Exception e) {
        e.printStackTrace();
        LogUtil.e("hxk", "upload file fail-->>");
    }
}

From source file:com.Candy.ota.CandyOTA.java

private void setDeviceInfoContainer() {
    try {//from w  w  w.  j a  v  a  2s  .  c  om
        FileInputStream fstream = new FileInputStream("/system/build.prop");
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        while ((strLine = br.readLine()) != null) {
            String[] line = strLine.split("=");
            if (line[0].equalsIgnoreCase("ro.candy.device")) {
                mStrCodename = line[1];
            } else if (line[0].equalsIgnoreCase("candy.ota.version")) {
                mStrCurVer = line[1];
            } else if (line[0].equalsIgnoreCase("ro.candy.model")) {
                mStrDevice = line[1];
            } else if (line[0].equalsIgnoreCase("ro.modversion")) {
                mStrCurFile = line[1];
            }
        }
        in.close();
    } catch (Exception e) {
        Toast.makeText(getView().getContext(), getString(R.string.system_prop_error), Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }

    mDeviceOut.setText(getString(R.string.device_name_title) + " " + mStrDevice);
    mCodenameOut.setText(getString(R.string.codename_title) + " " + mStrCodename);
    mCurVerOut.setText(getString(R.string.version_title) + " " + mStrCurVer);
    mCurFileOut.setText(getString(R.string.file_name_title) + " " + mStrCurFile);

    SharedPreferences prefs = this.getActivity().getSharedPreferences("UpdateChecker", 0);
    String updateFile = prefs.getString("Filename", "");

    mUpdateFile.setTextColor(Color.RED);

    if (!UpdateChecker.connectivityAvailable(getActivity())) {
        mStrUpToDate = getString(R.string.no_data_title);
        mStatusIcon.setImageResource(R.drawable.ic_no_data);
    } else if (updateFile.equals("")) {
        mStrUpToDate = getString(R.string.error_reading_title);
        mStatusIcon.setImageResource(R.drawable.ic_no_data);
    } else if (updateFile.compareToIgnoreCase(mStrCurVer) <= 0) {
        mUpdateFile.setTextColor(Color.GREEN);
        mStrUpToDate = getString(R.string.up_to_date_title);
        mStatusIcon.setImageResource(R.drawable.ic_uptodate);
    } else {
        mStatusIcon.setImageResource(R.drawable.ic_need_update);
        mStrUpToDate = updateFile;
    }

    mUpdateFile.setText(" " + mStrUpToDate);
}

From source file:jp.co.cyberagent.jenkins.plugins.DeployStrategy.java

public String getVersion() {
    File versionFile = new File(mBuild.getWorkspace().getRemote() + "/VERSION");

    if (versionFile.exists()) {
        FileInputStream stream = null;
        DataInputStream in = null;
        InputStreamReader reader = null;
        BufferedReader br = null;
        try {/* w w w.j  a  v a 2s  .c  o  m*/
            stream = new FileInputStream(versionFile);
            in = new DataInputStream(stream);
            reader = new InputStreamReader(in);
            br = new BufferedReader(reader);
            return br.readLine();
        } catch (Exception e) {
            getLogger().println(TAG + "Error: " + e.getMessage());
        } finally {
            try {
                if (stream != null)
                    stream.close();
                if (br != null)
                    br.close();
                if (reader != null)
                    reader.close();
                if (in != null)
                    in.close();
            } catch (IOException e) {
                getLogger().println(TAG + "Error: " + e.getMessage());
            }
        }
    }
    return null;
}

From source file:org.apache.hadoop.hbase.util.FSUtils.java

/**
 * Verifies current version of file system
 *
 * @param fs filesystem object/* w  w  w  . j av  a2  s. com*/
 * @param rootdir root hbase directory
 * @return null if no version file exists, version string otherwise.
 * @throws IOException e
 * @throws org.apache.hadoop.hbase.exceptions.DeserializationException
 */
public static String getVersion(FileSystem fs, Path rootdir) throws IOException, DeserializationException {
    Path versionFile = new Path(rootdir, HConstants.VERSION_FILE_NAME);
    FileStatus[] status = null;
    try {
        // hadoop 2.0 throws FNFE if directory does not exist.
        // hadoop 1.0 returns null if directory does not exist.
        status = fs.listStatus(versionFile);
    } catch (FileNotFoundException fnfe) {
        return null;
    }
    if (status == null || status.length == 0)
        return null;
    String version = null;
    byte[] content = new byte[(int) status[0].getLen()];
    FSDataInputStream s = fs.open(versionFile);
    try {
        IOUtils.readFully(s, content, 0, content.length);
        if (ProtobufUtil.isPBMagicPrefix(content)) {
            version = parseVersionFrom(content);
        } else {
            // Presume it pre-pb format.
            InputStream is = new ByteArrayInputStream(content);
            DataInputStream dis = new DataInputStream(is);
            try {
                version = dis.readUTF();
            } finally {
                dis.close();
            }
            // Update the format
            LOG.info("Updating the hbase.version file format with version=" + version);
            setVersion(fs, rootdir, version, 0, HConstants.DEFAULT_VERSION_FILE_WRITE_ATTEMPTS);
        }
    } catch (EOFException eof) {
        LOG.warn("Version file was empty, odd, will try to set it.");
    } finally {
        s.close();
    }
    return version;
}

From source file:org.commoncrawl.service.crawler.CrawlLog.java

private static LogFileHeader initializeLogFileHeaderFromLogFile(File logFilePath) throws IOException {

    LogFileHeader headerOut = null;/*from   ww  w. j  a  va 2 s. co  m*/
    if (!logFilePath.exists()) {
        DataOutputStream outputStream = new DataOutputStream(new FileOutputStream(logFilePath));
        try {
            headerOut = initializeEmptyLogFile(outputStream);
        } finally {
            outputStream.close();
        }
    } else {
        headerOut = new LogFileHeader();

        DataInputStream inputStream = new DataInputStream(new FileInputStream(logFilePath));

        try {
            headerOut.readHeader(inputStream);
        } finally {
            inputStream.close();
        }
    }

    return headerOut;
}

From source file:J2MESortMixedRecordDataTypeExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*from  w ww  . java2s  . c  om*/
        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:com.slim.ota.SlimOTA.java

private void setDeviceInfoContainer() {
    try {/* w w w .  ja  va2  s.c  o m*/
        FileInputStream fstream = new FileInputStream("/system/build.prop");
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        while ((strLine = br.readLine()) != null) {
            String[] line = strLine.split("=");
            if (line[0].equalsIgnoreCase("ro.product.model")) {
                mStrCodename = line[1];
            } else if (line[0].equalsIgnoreCase("ro.build.version.release")) {
                mStrCurVer = line[1];
            } else if (line[0].equalsIgnoreCase("ro.product.device")) {
                mStrDevice = line[1];
            } else if (line[0].equalsIgnoreCase("ro.modversion")) {
                mStrCurFile = line[1];
            }
        }
        in.close();
    } catch (Exception e) {
        Toast.makeText(getView().getContext(), getString(R.string.system_prop_error), Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }

    mDeviceOut.setText(getString(R.string.device_name_title) + " " + mStrDevice);
    mCodenameOut.setText(getString(R.string.codename_title) + " " + mStrCodename);
    mCurVerOut.setText(getString(R.string.version_title) + " " + mStrCurVer);
    mCurFileOut.setText(getString(R.string.file_name_title) + " " + mStrCurFile);

    SharedPreferences prefs = this.getActivity().getSharedPreferences("UpdateChecker", 0);
    String updateFile = prefs.getString("Filename", "");
    String needUpdate = prefs.getString("NeedUpdate", "");

    mUpdateFile.setTextColor(Color.RED);

    if (UpdateChecker.connectivityAvailable(getActivity())) {
        if (needUpdate.equals("yes")) {
            if (updateFile.equals("")) {
                mStrUpToDate = getString(R.string.error_reading_title);
                mStatusIcon.setImageResource(R.drawable.ic_no_data);
            } else {
                mStrUpToDate = updateFile;
                mStatusIcon.setImageResource(R.drawable.ic_need_update);
            }
        } else {
            mUpdateFile.setTextColor(Color.GREEN);
            mStrUpToDate = getString(R.string.up_to_date_title);
            mStatusIcon.setImageResource(R.drawable.ic_uptodate);
        }
    } else {
        mStrUpToDate = getString(R.string.no_data_title);
        mStatusIcon.setImageResource(R.drawable.ic_no_data);
    }

    mUpdateFile.setText(" " + mStrUpToDate);
}

From source file:it.infn.ct.jsaga.adaptor.jocci.job.jOCCIJobControlAdaptor.java

public String getPublicKey(String file) {
    FileInputStream fis = null;//from  w ww.ja  v a  2  s .  c  om
    String _publicKey = "";

    try {
        File f = new File(file);
        fis = new FileInputStream(f);
        DataInputStream dis = new DataInputStream(fis);
        byte[] keyBytes = new byte[(int) f.length()];
        dis.readFully(keyBytes);
        dis.close();
        _publicKey = new String(keyBytes).trim();
    } catch (IOException ex) {
        java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            fis.close();
        } catch (IOException ex) {
            java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName()).log(Level.SEVERE, null,
                    ex);
        }
    }

    return (_publicKey);
}