Example usage for java.io InputStreamReader close

List of usage examples for java.io InputStreamReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:com.zhengxuetao.gupiao.service.impl.DayServiceImpl.java

@Override
public boolean saveDayDataFromFile(File file) {
    if (file != null && file.exists() && file.isFile()) {
        DayData dayData = new DayData();
        String fileName = file.getName(); //SH#600004.txt
        dayData.setFinanceId(Long.parseLong(fileName.substring(3, 9)));
        String encoding = "GBK";
        InputStreamReader reader = null;
        DateFormat format = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
        DateFormat parseFormat = new SimpleDateFormat("yyyy-mm-dd");
        try {//ww  w .  java2 s . c om
            reader = new InputStreamReader(new FileInputStream(file), encoding);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String readLine;
            while ((readLine = bufferedReader.readLine()) != null) {
                //??????????
                String[] arr = readLine.split(",");
                dayData.setTime(Timestamp.valueOf(format.format(parseFormat.parse(arr[0]))));
                dayData.setStartPrice(Float.valueOf(arr[1]));
                dayData.setHighPrice(Float.valueOf(arr[2]));
                dayData.setLowPrice(Float.valueOf(arr[3]));
                dayData.setEndPrice(Float.valueOf(arr[4]));
                dayData.setVolume(Long.valueOf(arr[5]));
                dayData.setAmount(Double.valueOf(arr[6]));
                userDAO.saveDayData(dayData);
            }
        } catch (IOException | ParseException ex) {
            logger.error(ex.getMessage());
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                logger.error(ex.getMessage());
            }
        }
    } else {
        logger.error("?!");
    }
    return true;
}

From source file:com.prey.PreyPhone.java

public long maxCPUFreqMHz() {
    String line = "";
    File file = null;//from   w w w  .  j  a  v  a2  s . c  om
    FileInputStream fi = null;
    InputStreamReader ir = null;
    BufferedReader br = null;
    long cpuMaxFreq = 0;
    try {
        file = new File("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq");
        fi = new FileInputStream(file);
        ir = new InputStreamReader(fi);
        br = new BufferedReader(ir);
        while ((line = br.readLine()) != null) {
            if (line != null && !"".equals(line)) {
                break;
            }
        }
        cpuMaxFreq = Long.parseLong(line) / 1000;
    } catch (Exception e) {
    } finally {
        try {
            br.close();
        } catch (Exception e) {
        }
        try {
            ir.close();
        } catch (Exception e) {
        }
        try {
            fi.close();
        } catch (Exception e) {
        }
    }
    return cpuMaxFreq;
}

From source file:com.lenovo.tensorhusky.common.utils.ProcfsBasedProcessTree.java

/**
 * Construct the ProcessInfo using the process' PID and procfs rooted at the
 * specified directory and return the same. It is provided mainly to assist
 * testing purposes./*w  ww.j  a va 2  s  .  c  o  m*/
 * <p>
 * Returns null on failing to read from procfs,
 *
 * @param pinfo     ProcessInfo that needs to be updated
 * @param procfsDir root of the proc file system
 * @return updated ProcessInfo, null on errors.
 */
private static ProcessInfo constructProcessInfo(ProcessInfo pinfo, String procfsDir) {
    ProcessInfo ret = null;
    // Read "procfsDir/<pid>/stat" file - typically /proc/<pid>/stat
    BufferedReader in = null;
    InputStreamReader fReader = null;
    try {
        File pidDir = new File(procfsDir, pinfo.getPid());
        fReader = new InputStreamReader(new FileInputStream(new File(pidDir, PROCFS_STAT_FILE)),
                Charset.forName("UTF-8"));
        in = new BufferedReader(fReader);
    } catch (FileNotFoundException f) {
        // The process vanished in the interim!
        return ret;
    }

    ret = pinfo;
    try {
        String str = in.readLine(); // only one line
        Matcher m = PROCFS_STAT_FILE_FORMAT.matcher(str);
        boolean mat = m.find();
        if (mat) {
            // Set (name) (ppid) (pgrpId) (session) (utime) (stime) (vsize)
            // (rss)
            pinfo.updateProcessInfo(m.group(2), m.group(3), Integer.parseInt(m.group(4)),
                    Integer.parseInt(m.group(5)), Long.parseLong(m.group(7)), new BigInteger(m.group(8)),
                    Long.parseLong(m.group(10)), Long.parseLong(m.group(11)));
        } else {
            LOG.warn("Unexpected: procfs stat file is not in the expected format" + " for process with pid "
                    + pinfo.getPid());
            ret = null;
        }
    } catch (IOException io) {
        LOG.warn("Error reading the stream " + io);
        ret = null;
    } finally {
        // Close the streams
        try {
            fReader.close();
            try {
                in.close();
            } catch (IOException i) {
                LOG.warn("Error closing the stream " + in);
            }
        } catch (IOException i) {
            LOG.warn("Error closing the stream " + fReader);
        }
    }

    return ret;
}

From source file:com.moesol.geoserver.sync.client.AbstractClientSynchronizer.java

private boolean processSha1SyncResponse(Response response) throws IOException {
    int expected = m_server.level() + 1;
    CountingInputStream counter = new CountingInputStream(response.getResultStream());
    InputStreamReader reader = new InputStreamReader(new BufferedInputStream(counter), UTF8.UTF8);
    try {/*from   ww w .ja  va 2s .  com*/
        m_server = new Gson().fromJson(reader, Sha1SyncJson.class);
        if (expected != m_server.level()) {
            throw new IllegalStateException(
                    "Level warp! expected(" + expected + "), actual(" + m_server.level() + ")");
        }
        if (!versionFeatures.getToken().equals(m_server.version())) {
            throw new IllegalStateException("Version warp! expected(" + versionFeatures.getToken()
                    + "), actual(" + m_server.version() + ")");
        }
        if (isServerEmpty()) {
            clearLocal();
            return true;
        }
        if (isServerHashesEmpty()) {
            return true;
        }
        return false;
    } finally {
        m_rxBytes += counter.getByteCount();
        reader.close();
    }
}

From source file:com.lenovo.tensorhusky.common.utils.LinuxResourceCalculatorPlugin.java

/**
 * Read /proc/stat file, parse and calculate cumulative CPU
 *///  w  ww.  j a  v a 2  s .  c o m
private void readProcStatFile() {
    // Read "/proc/stat" file
    BufferedReader in = null;
    InputStreamReader fReader = null;
    try {
        fReader = new InputStreamReader(new FileInputStream(procfsStatFile), Charset.forName("UTF-8"));
        in = new BufferedReader(fReader);
    } catch (FileNotFoundException f) {
        // shouldn't happen....
        return;
    }

    Matcher mat = null;
    try {
        String str = in.readLine();
        while (str != null) {
            mat = CPU_TIME_FORMAT.matcher(str);
            if (mat.find()) {
                long uTime = Long.parseLong(mat.group(1));
                long nTime = Long.parseLong(mat.group(2));
                long sTime = Long.parseLong(mat.group(3));
                cpuTimeTracker.updateElapsedJiffies(BigInteger.valueOf(uTime + nTime + sTime),
                        getCurrentTime());
                break;
            }
            str = in.readLine();
        }
    } catch (IOException io) {
        LOG.warn("Error reading the stream " + io);
    } finally {
        // Close the streams
        try {
            fReader.close();
            try {
                in.close();
            } catch (IOException i) {
                LOG.warn("Error closing the stream " + in);
            }
        } catch (IOException i) {
            LOG.warn("Error closing the stream " + fReader);
        }
    }
}

From source file:de.teamgrit.grit.checking.compile.HaskellCompileChecker.java

/**
 * checkProgram invokes the Haskell compiler on a given file and reports
 * the output./*from  w w w. j a  v  a 2  s  . c om*/
 * 
 * @param pathToProgramFile
 *            Specifies the file or folder containing that should be
 *            compiled. (accepts .lhs and .hs files)
 * @param compilerName
 *            The compiler to be used (usually ghc).
 * @param compilerFlags
 *            Additional flags to be passed to the compiler.
 * @throws FileNotFoundException
 *             Is thrown when the file in pathToProgramFile cannot be
 *             opened
 * @throws BadCompilerSpecifiedException
 *             Is thrown when the given compiler cannot be called
 * @return A {@link CompilerOutput} that contains all compiler messages and
 *         flags on how the compile run went.
 * @throws BadFlagException
 *             When ghc doesn't recognize a flag, this exception is thrown.
 */
@Override
public CompilerOutput checkProgram(Path pathToProgramFile, String compilerName, List<String> compilerFlags)
        throws FileNotFoundException, BadCompilerSpecifiedException, BadFlagException {

    Process compilerProcess = null;

    try {
        // create compiler invocation.
        List<String> compilerInvocation = createCompilerInvocation(pathToProgramFile, compilerName,
                compilerFlags);

        ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation);

        // make sure the compiler stays in its directory.
        compilerProcessBuilder.directory(pathToProgramFile.getParent().toFile());

        compilerProcess = compilerProcessBuilder.start();
        // this will never happen because createCompilerInvocation never
        // throws this Exception. Throw declaration needs to be in method
        // declaration because of the implemented Interface although we
        // never use it in the HaskellCompileChecker
    } catch (CompilerOutputFolderExistsException e) {
        LOGGER.severe("A problem while compiling, which never should happen, occured" + e.getMessage());
    } catch (BadCompilerSpecifiedException e) {
        throw new BadCompilerSpecifiedException(e.getMessage());
    } catch (IOException e) {

        // If we cannot call the compiler we return a CompilerOutput
        // initialized with false, false, indicating
        // that the compiler wasn't invoked properly and that there was no
        // clean Compile.
        CompilerOutput compilerInvokeError = new CompilerOutput();
        compilerInvokeError.setClean(false);
        compilerInvokeError.setCompilerInvoked(false);
        return compilerInvokeError;
    }

    // Now we read compiler output. If everything is ok ghc reports
    // nothing in the errorStream.
    InputStream compilerOutputStream = compilerProcess.getErrorStream();
    InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream);
    BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader);
    String line;

    CompilerOutput compilerOutput = new CompilerOutput();
    compilerOutput.setCompilerInvoked(true);

    List<String> compilerOutputLines = new LinkedList<>();

    try {
        while ((line = compilerOutputBuffer.readLine()) != null) {
            compilerOutputLines.add(line);
        }
        // Errors are separated via an empty line (""). But after the
        // the last error the OutputBuffer has nothing more to write.
        // In order to recognize the last error we insert an empty String
        // at the end of the list.
        // Only needs to be done when there are errors.
        if (compilerOutputLines.size() != 0) {
            line = "";
            compilerOutputLines.add(line);
        }

        compilerOutputStream.close();
        compilerStreamReader.close();
        compilerOutputBuffer.close();
        compilerProcess.destroy();

    } catch (IOException e) {

        // Reading might go wrong here if ghc should unexpectedly die
        LOGGER.severe("Error while reading from compiler stream.");
        compilerOutput.setClean(false);
        compilerOutput.setCompileStreamBroken(true);
        return compilerOutput;
    }

    // ghc -c generates a .o(object) and a .hi(haskell interface) file.
    // But we don't need those files so they can be deleted.
    // The generated files have the same name like our input file so we
    // can just exchange the file endings in order to get the
    // correct file paths for deletion
    if (Files.isDirectory(pathToProgramFile, LinkOption.NOFOLLOW_LINKS)) {

        // we use a file walker in order to find all files in the folder
        // and its subfolders
        RegexDirectoryWalker dirWalker = new RegexDirectoryWalker(".+\\.([Ll])?[Hh][Ss]");
        try {
            Files.walkFileTree(pathToProgramFile, dirWalker);
        } catch (IOException e) {
            LOGGER.severe("Could not walk submission " + pathToProgramFile.toString()
                    + " while building copiler invocation: " + e.getMessage());
        }

        for (Path candidatePath : dirWalker.getFoundFiles()) {
            File candidateFile = candidatePath.toFile();
            if (!candidateFile.isDirectory()) {
                String extension = FilenameUtils.getExtension(candidateFile.toString());
                if (extension.matches("[Ll]?[Hh][Ss]")) {
                    File ghcGeneratedObject = new File(
                            FilenameUtils.removeExtension(candidateFile.toString()) + ".o");
                    File ghcGeneratedInterface = new File(
                            FilenameUtils.removeExtension(candidateFile.toString()) + ".hi");
                    ghcGeneratedObject.delete();
                    ghcGeneratedInterface.delete();
                }
            }
        }
    } else {
        String extension = FilenameUtils.getExtension(pathToProgramFile.toString());
        if (extension.matches("[Ll]?[Hh][Ss]")) {
            File ghcGeneratedObject = new File(
                    FilenameUtils.removeExtension(pathToProgramFile.toString()) + ".o");
            File ghcGeneratedInterface = new File(
                    FilenameUtils.removeExtension(pathToProgramFile.toString()) + ".hi");
            ghcGeneratedObject.delete();
            ghcGeneratedInterface.delete();
        }

    }

    // if there are no errors there is no Output to handle
    if (compilerOutputLines.size() != 0) {
        compilerOutput = splitCompilerOutput(compilerOutputLines, compilerOutput);
    } else {
        compilerOutput.setClean(true);
    }
    return compilerOutput;
}

From source file:org.apache.hadoop.yarn.util.ProcfsBasedProcessTree.java

/**
 * Construct the ProcessInfo using the process' PID and procfs rooted at the
 * specified directory and return the same. It is provided mainly to assist
 * testing purposes.//  w w w.  java2 s. c  o m
 *
 * Returns null on failing to read from procfs,
 *
 * @param pinfo ProcessInfo that needs to be updated
 * @param procfsDir root of the proc file system
 * @return updated ProcessInfo, null on errors.
 */
private static ProcessInfo constructProcessInfo(ProcessInfo pinfo, String procfsDir) {
    ProcessInfo ret = null;
    // Read "procfsDir/<pid>/stat" file - typically /proc/<pid>/stat
    BufferedReader in = null;
    InputStreamReader fReader = null;
    try {
        File pidDir = new File(procfsDir, pinfo.getPid());
        fReader = new InputStreamReader(new FileInputStream(new File(pidDir, PROCFS_STAT_FILE)),
                Charset.forName("UTF-8"));
        in = new BufferedReader(fReader);
    } catch (FileNotFoundException f) {
        // The process vanished in the interim!
        return ret;
    }

    ret = pinfo;
    try {
        String str = in.readLine(); // only one line
        Matcher m = PROCFS_STAT_FILE_FORMAT.matcher(str);
        boolean mat = m.find();
        if (mat) {
            String processName = "(" + m.group(2) + ")";
            // Set (name) (ppid) (pgrpId) (session) (utime) (stime) (vsize) (rss)
            pinfo.updateProcessInfo(processName, m.group(3), Integer.parseInt(m.group(4)),
                    Integer.parseInt(m.group(5)), Long.parseLong(m.group(7)), new BigInteger(m.group(8)),
                    Long.parseLong(m.group(10)), Long.parseLong(m.group(11)));
        } else {
            LOG.warn("Unexpected: procfs stat file is not in the expected format" + " for process with pid "
                    + pinfo.getPid());
            ret = null;
        }
    } catch (IOException io) {
        LOG.warn("Error reading the stream " + io);
        ret = null;
    } finally {
        // Close the streams
        try {
            fReader.close();
            try {
                in.close();
            } catch (IOException i) {
                LOG.warn("Error closing the stream " + in);
            }
        } catch (IOException i) {
            LOG.warn("Error closing the stream " + fReader);
        }
    }

    return ret;
}

From source file:nmtysh.android.test.speedtest.SpeedTestActivity.java

private void runHttpURLConnection() {
    final String url = urlEdit.getText().toString();
    if (url == null || (!url.startsWith("http://") && !url.startsWith("https://"))) {
        list.add("URL error!");
        adapter.notifyDataSetChanged();//from   w w w.java 2s.  c  o  m
        return;
    }
    task = new AsyncTask<Void, Integer, Void>() {
        long startTime;
        ProgressDialog progress;

        // ??
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progress = new ProgressDialog(SpeedTestActivity.this);
            progress.setMessage(getString(R.string.progress_message));
            progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progress.setIndeterminate(false);
            progress.setCancelable(true);
            progress.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    task.cancel(true);
                }
            });
            progress.setMax(10);
            progress.setProgress(0);
            progress.show();

            startTime = System.currentTimeMillis();
        }

        // ???
        @Override
        protected Void doInBackground(Void... params) {
            // 10?????
            for (int i = 0; i < 10; i++) {
                HttpURLConnection connection = null;
                InputStreamReader in = null;
                // BufferedReader br = null;
                try {
                    connection = (HttpURLConnection) (new URL(url)).openConnection();
                    connection.setRequestMethod("GET");
                    connection.connect();
                    in = new InputStreamReader(connection.getInputStream());
                    // br = new BufferedReader(in);
                    // while (br.readLine() != null) {
                    long len = 0;
                    while (in.read() != -1) {
                        len++;
                    }
                    Log.i("HttpURLConnection", len + " Bytes");
                } catch (IOException e) {
                } finally {
                    /*
                     * if (br != null) { try { br.close(); } catch
                     * (IOException e) { } br = null; }
                     */
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                        }
                        in = null;
                    }
                    if (connection != null) {
                        connection.disconnect();
                        connection = null;
                    }
                }
                publishProgress(i + 1);
                // Dos????????
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (progress == null) {
                return;
            }
            progress.setProgress(values[0]);
        }

        // 
        @Override
        protected void onPostExecute(Void result) {
            long endTime = System.currentTimeMillis();

            // 
            progress.cancel();
            progress = null;

            list.add("HttpURLConnection:" + url + " " + (endTime - startTime) + "msec/10" + " "
                    + (endTime - startTime) / 10 + "msec");
            adapter.notifyDataSetChanged();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            progress.dismiss();
            progress = null;
        }
    }.execute();
}

From source file:eu.musesproject.server.policyrulesselector.PolicySelector.java

private String getJSONDevicePolicy(String requestId, Decision decision, String action) {
    String jsonDevicePolicy = null;
    BufferedReader br = null;//from   w  w  w.  j a va2s .c o  m
    InputStream in = null;
    InputStreamReader is = null;
    String policyContent = null;
    try {
        policyContent = getPolicyDTHeader();
        policyContent += getActionSection(decision, action, requestId);
        policyContent += getPolicyDTBottom();
        JSONObject xmlJSONObj = XML.toJSONObject(policyContent);
        jsonDevicePolicy = xmlJSONObj.toString();
    } catch (JSONException je) {
        logger.error("JSONException:" + je.getCause());
    } catch (Exception e) {
        jsonDevicePolicy = "<errorBuildingPolicy/>";
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException e) {
            logger.error("IOException:" + e.getCause());

        }
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            logger.error("IOException:" + e.getCause());

        }
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            logger.error("IOException:" + e.getCause());

        }
    }

    return jsonDevicePolicy;
}

From source file:org.apache.phoenix.hive.HiveTestUtil.java

public String readEntireFileIntoString(File queryFile) throws IOException {
    InputStreamReader isr = new InputStreamReader(new BufferedInputStream(new FileInputStream(queryFile)),
            HiveTestUtil.UTF_8);// ww  w  .  j a  v  a2 s  .c  o m
    StringWriter sw = new StringWriter();
    try {
        IOUtils.copy(isr, sw);
    } finally {
        if (isr != null) {
            isr.close();
        }
    }
    return sw.toString();
}