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:com.yahoo.glimmer.util.MergeSortTool.java

public static int mergeSort(FileSystem fs, List<Path> sourcePaths, Path outputPath,
        CompressionCodecFactory compressionCodecFactory) throws IOException {
    assert sourcePaths.size() > 0 : "No source paths given.";

    LOG.info("Sorted merge into " + outputPath.toString());
    OutputStream outputStream = fs.create(outputPath);

    CompressionCodec inputCompressionCodec = compressionCodecFactory.getCodec(sourcePaths.get(0));
    if (inputCompressionCodec != null) {
        LOG.info("Input compression codec " + inputCompressionCodec.getClass().getName());
    }/*from   w w w.ja va 2  s .  co m*/

    CompressionCodec outputCompressionCodec = compressionCodecFactory.getCodec(outputPath);
    if (outputCompressionCodec != null) {
        LOG.info("Output compression codec " + outputCompressionCodec.getClass().getName());
        outputStream = outputCompressionCodec.createOutputStream(outputStream);
    }

    List<BufferedReader> readers = new ArrayList<BufferedReader>();
    OutputStreamWriter writer = new OutputStreamWriter(outputStream);

    for (Path partPath : sourcePaths) {
        LOG.info("\tAdding source " + partPath.toString());
        InputStream inputStream = fs.open(partPath);
        if (inputCompressionCodec != null) {
            inputStream = inputCompressionCodec.createInputStream(inputStream);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        readers.add(reader);
    }

    int count = ReadersWriterMergeSort.mergeSort(readers, writer);

    writer.close();
    for (BufferedReader reader : readers) {
        reader.close();
    }
    readers.clear();
    LOG.info("Processed " + count + " lines into " + outputPath.toString());
    return count;
}

From source file:Main.java

private static String getRawText(String link) throws IOException {

    URL url;/*  www. ja  v  a2 s .c o m*/
    url = new URL(link);

    URLConnection connection = url.openConnection();

    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(connection.getInputStream(), "UTF-8"));

    StringBuffer stringBuffer = new StringBuffer();
    String inputLine;
    // read from buffer line by line
    while ((inputLine = bufferedReader.readLine()) != null) {
        stringBuffer.append(inputLine + "\n");
    }
    bufferedReader.close();
    return stringBuffer.toString();
}

From source file:Main.java

/**
 * Converts a java.io.InputStream to a java.lang.String object
 * @throws java.lang.IllegalStateException if an error occurs while reading the stream or closing the reader
 * @param is/*ww  w.  ja v a2  s  .c  o m*/
 * @return the String representation of the provided InputStream
 */
public static String inputStreamToString(InputStream is) {
    String line = "";

    StringBuilder builder = new StringBuilder();

    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

    try {
        while ((line = rd.readLine()) != null) {
            builder.append(line);
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    } finally {
        try {
            if (rd != null)
                rd.close();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    return builder.toString();
}

From source file:Main.java

/**
 * @return/*from   w  w w.j  a va  2 s. co m*/
 * @throws IOException
 */
public static String getDataFromFile(String dataFileName) throws IOException {
    FileInputStream inputStream = null;

    try {
        inputStream = new FileInputStream(dataFileName);

    } catch (IOException e) {
        e.printStackTrace();
    }
    String _jsonGspTxt = null;
    if (inputStream != null)

    {

        BufferedReader myReader = new BufferedReader(new InputStreamReader(inputStream));
        String _row = "";
        StringBuffer _buffer = new StringBuffer();
        while ((_row = myReader.readLine()) != null) {
            _buffer.append(_row);
        }
        _jsonGspTxt = _buffer.toString();
        // _fIn.close();
        myReader.close();
    } else {

        throw new FileNotFoundException();
    }
    return _jsonGspTxt;
}

From source file:net.dv8tion.discord.util.GoogleSearch.java

public static List<SearchResult> performSearch(String engineId, String terms, int requiredResultsCount) {
    try {//  w w  w .jav a  2s .c o m
        if (GOOGLE_API_KEY == null)
            throw new IllegalStateException(
                    "Google API Key is null, Cannot preform google search without a key! Set one in the settings!");
        if (engineId == null || engineId.isEmpty())
            throw new IllegalArgumentException("Google Custom Search Engine id cannot be null or empty!");

        LocalDateTime currentTime = LocalDateTime.now();
        if (currentTime.isAfter(dayStartTime.plusDays(1))) {
            dayStartTime = currentTime;
            currentGoogleUsage = 1;
        } else if (currentGoogleUsage >= 80) {
            throw new IllegalStateException("Google usage has reached the premature security cap of 80");
        }

        terms = terms.replace(" ", "%20");
        String searchUrl = String.format(GOOGLE_URL, engineId, GOOGLE_API_KEY, requiredResultsCount, terms);

        URL searchURL = new URL(searchUrl);
        URLConnection conn = searchURL.openConnection();
        currentGoogleUsage++;
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:39.0) Gecko/20100101 " + randomName(10));
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder json = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            json.append(line).append("\n");
        }
        in.close();

        JSONArray jsonResults = new JSONObject(json.toString()).getJSONArray("items");
        List<SearchResult> results = new LinkedList<>();
        for (int i = 0; i < jsonResults.length(); i++) {
            results.add(SearchResult.fromGoogle(jsonResults.getJSONObject(i)));
        }
        return results;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:Main.java

public static String stringFromFile(final File file) throws IOException {
    final BufferedReader br = new BufferedReader(new FileReader(file));
    try {// w  w w. j  a v a  2 s. c  o  m
        final StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        return sb.toString();
    } finally {
        br.close();
    }
}

From source file:com.swisscom.safeconnect.backend.PlumberTask.java

private static String inputStreamToString(InputStream is) throws IOException {
    StringBuilder sb = new StringBuilder();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader rd = new BufferedReader(isr);

    try {//from ww w. j  a  va 2 s.com
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
    } finally {
        rd.close();
        isr.close();
        is.close();
    }

    return sb.toString();
}

From source file:Main.java

public static List<String> createListFromFile(File f) {
    List<String> retList = new ArrayList<String>();
    FileInputStream fis;//from w  w w.j av  a  2 s  .  c  o  m
    BufferedReader br;
    try {
        fis = new FileInputStream(f);
        InputStreamReader isr = new InputStreamReader(fis);
        br = new BufferedReader(isr);

        String nStr;
        nStr = br.readLine();
        while (nStr != null) {
            retList.add(nStr);
            nStr = br.readLine();
        }

        br.close();
        fis.close();
    } catch (FileNotFoundException e) {
        logger.severe(e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        logger.severe(e.toString());
        e.printStackTrace();
    }

    return retList;
}

From source file:com.ant.myteam.gcm.POST2GCM.java

public static void post(String apiKey, Content content) {

    try {//from   w  w  w.ja v a 2 s. c o  m

        // 1. URL
        URL url = new URL("https://android.googleapis.com/gcm/send");

        // 2. Open connection
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 3. Specify POST method
        conn.setRequestMethod("POST");

        // 4. Set the headers
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);

        conn.setDoOutput(true);

        // 5. Add JSON data into POST request body

        //`5.1 Use Jackson object mapper to convert Contnet object into JSON
        ObjectMapper mapper = new ObjectMapper();

        // 5.2 Get connection output stream
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

        // 5.3 Copy Content "JSON" into
        mapper.writeValue(wr, content);

        // 5.4 Send the request
        wr.flush();

        // 5.5 close
        wr.close();

        // 6. Get the response
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 7. Print result
        System.out.println(response.toString());

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

From source file:com.breadwallet.tools.threads.ImportPrivKeyTask.java

private static String callURL(String myURL) {
    //        System.out.println("Requested URL_EA:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;/*from w w  w .  j  a  va 2 s.  co  m*/
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null)
            urlConn.setReadTimeout(60 * 1000);
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
            BufferedReader bufferedReader = new BufferedReader(in);

            int cp;
            while ((cp = bufferedReader.read()) != -1) {
                sb.append((char) cp);
            }
            bufferedReader.close();
        }
        assert in != null;
        in.close();
    } catch (Exception e) {
        return null;
    }

    return sb.toString();
}