Example usage for java.io BufferedReader close

List of usage examples for java.io BufferedReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:org.acra.HttpUtils.java

/**
 * Send an HTTP(s) request with POST parameters.
 * /*from w ww  .j  a  va  2 s . com*/
 * @param parameters
 * @param url
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
static void doPost(Map<?, ?> parameters, URL url)
        throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException {

    URLConnection cnx = getConnection(url);

    // Construct data
    StringBuilder dataBfr = new StringBuilder();
    Iterator<?> iKeys = parameters.keySet().iterator();
    while (iKeys.hasNext()) {
        if (dataBfr.length() != 0) {
            dataBfr.append('&');
        }
        String key = (String) iKeys.next();
        dataBfr.append(URLEncoder.encode(key, "UTF-8")).append('=')
                .append(URLEncoder.encode((String) parameters.get(key), "UTF-8"));
    }
    // POST data
    cnx.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(cnx.getOutputStream());
    Log.d(LOG_TAG, "Posting crash report data");
    wr.write(dataBfr.toString());
    wr.flush();
    wr.close();

    Log.d(LOG_TAG, "Reading response");
    BufferedReader rd = new BufferedReader(new InputStreamReader(cnx.getInputStream()));

    String line;
    while ((line = rd.readLine()) != null) {
        Log.d(LOG_TAG, line);
    }
    rd.close();
}

From source file:com.zack6849.alphabot.api.Utils.java

public static String shortenUrl(String longUrl) {
    String shortened = null;/*  w  ww  .  ja v  a  2  s  .  co  m*/
    try {
        URL url;
        url = new URL("http://is.gd/create.php?format=simple&url=" + longUrl);
        BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(url.openStream()));
        shortened = bufferedreader.readLine();
        bufferedreader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return shortened;
}

From source file:com.admc.util.IOUtil.java

/**
 * Generates a StringBuilder from specified InputStream,
 * using UTF-8 encoding.// w  ww .  j  a va 2 s  .c  om
 *
 * If the input stream can be initialized by this method, then this method
 * will also close it.
 */
public static StringBuilder toStringBuilder(InputStream inputStream, int bufferChars) throws IOException {
    char[] buffer = new char[bufferChars];
    int i;
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    try {
        while ((i = reader.read(buffer)) > -1)
            sb.append(buffer, 0, i);
    } finally {
        try {
            reader.close();
        } catch (IOException ioe) {
            log.error("Failed to close reader", ioe);
        }
        reader = null;
    }
    return sb;
}

From source file:Main.java

public static synchronized StringBuilder readTempFile(String filename) {
    File tempFile;/* ww  w. j a v a 2s  .  c  om*/
    FileInputStream is = null;

    tempFile = new File(filename);

    String strLine = "";
    StringBuilder text = new StringBuilder();

    /** Reading contents of the temporary file, if already exists */
    try {
        is = new FileInputStream(tempFile);
        //            FileReader fReader = new FileReader(tempFile);
        BufferedReader bReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));

        /** Reading the contents of the file , line by line */
        while ((strLine = bReader.readLine()) != null) {
            text.append(strLine + "\n");
        }

        bReader.close(); //close bufferedreader
        is.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return text;

}

From source file:Main.java

public static String callJsonAPI(String urlString) {
    // Use HttpURLConnection as per Android 6.0 spec, instead of less efficient HttpClient
    HttpURLConnection urlConnection = null;
    StringBuilder jsonResult = new StringBuilder();

    try {/*from   w  w  w.  jav  a  2  s . c o m*/
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(TIMEOUT_CONNECTION);
        urlConnection.setReadTimeout(TIMEOUT_READ);
        urlConnection.connect();

        int status = urlConnection.getResponseCode();

        switch (status) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            String line;
            while ((line = br.readLine()) != null) {
                jsonResult.append(line).append("\n");
            }
            br.close();
        }
    } catch (MalformedURLException e) {
        System.err.print(e.getMessage());
        return e.getMessage();
    } catch (IOException e) {
        System.err.print(e.getMessage());
        return e.getMessage();
    } finally {
        if (urlConnection != null) {
            try {
                urlConnection.disconnect();
            } catch (Exception e) {
                System.err.print(e.getMessage());
            }
        }
    }
    return jsonResult.toString();
}

From source file:gov.nist.healthcare.ttt.webapp.common.controller.GetCCDADocumentsController.java

public static JSONObject getHTML(String urlToRead) throws Exception {
    StringBuilder result = new StringBuilder();
    URL url = new URL(urlToRead);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;/* ww w  .j  av a2s .c o  m*/
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    rd.close();
    return new JSONObject(result.toString());
}

From source file:com.pseudosudostudios.jdd.utils.ScoreSaves.java

/**
 * @param c the application's context that owns the data file
 * @return a List of games saved in the file
 *//*from w ww . j  a v a 2s  .com*/
public static List<Entry> getSaves(Context c) {
    List<Entry> entries = new ArrayList<Entry>();
    File f = new File(c.getFilesDir(), fileName);
    if (!f.exists() || f.isDirectory()) {
        return new ArrayList<Entry>();
    }
    try {
        BufferedReader reader = new BufferedReader(new FileReader(f));
        StringBuffer buff = new StringBuffer();
        while (reader.ready())
            buff.append(reader.readLine());
        reader.close();
        JSONArray array = new JSONArray(buff.toString());
        for (int i = 0; i < array.length(); i++) {
            Entry e = makeEntry(array.getJSONObject(i));
            if (e.getScore() != IGNORE_SCORE)
                entries.add(e);
        }

        Collections.sort(entries);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return entries;
}

From source file:minij.assembler.Assembler.java

public static void assemble(Configuration config, String assembly) throws AssemblerException {

    try {//from ww  w . j  a  v a 2 s. c om
        new File(FilenameUtils.getPath(config.outputFile)).mkdirs();

        // -xc specifies the input language as C and is required for GCC to read from stdin
        ProcessBuilder processBuilder = new ProcessBuilder("gcc", "-o", config.outputFile, "-m32", "-xc",
                MiniJCompiler.RUNTIME_DIRECTORY.toString() + File.separator + "runtime_32.c", "-m32",
                "-xassembler", "-");
        Process gccCall = processBuilder.start();
        // Write C code to stdin of C Compiler
        OutputStream stdin = gccCall.getOutputStream();
        stdin.write(assembly.getBytes());
        stdin.close();

        gccCall.waitFor();

        // Print error messages of GCC
        if (gccCall.exitValue() != 0) {

            StringBuilder errOutput = new StringBuilder();
            InputStream stderr = gccCall.getErrorStream();
            String line;
            BufferedReader bufferedStderr = new BufferedReader(new InputStreamReader(stderr));
            while ((line = bufferedStderr.readLine()) != null) {
                errOutput.append(line + System.lineSeparator());
            }
            bufferedStderr.close();
            stderr.close();

            throw new AssemblerException(
                    "Failed to compile assembly:" + System.lineSeparator() + errOutput.toString());
        }

        Logger.logVerbosely("Successfully compiled assembly");
    } catch (IOException e) {
        throw new AssemblerException("Failed to transfer assembly to gcc", e);
    } catch (InterruptedException e) {
        throw new AssemblerException("Failed to invoke gcc", e);
    }

}

From source file:Main.java

public static String getURLContent(String urlStr) throws Exception {
    BufferedReader br = null;
    URL url = new URL(urlStr);
    InputStream ins = url.openStream();
    br = new BufferedReader(new InputStreamReader(ins));

    StringBuilder sb = new StringBuilder();
    String msg = null;//from w w  w.ja  v a2 s . co  m
    while ((msg = br.readLine()) != null) {
        sb.append(msg);
        sb.append("\n"); // Append a new line
    }
    br.close();
    return sb.toString();
}

From source file:Main.java

public static String readFrom(Socket s) throws IOException {
    final BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String inputLine;//from w  w  w .  j a  va 2 s. c  o m

    while ((inputLine = in.readLine()) != null) {// && !inputLine.equals(RBIConstants.EOM)) {
        sb.append(inputLine);
        sb.append("\n");
    }

    in.close();
    return sb.toString();
}