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

public static String readFileContents(File file) throws IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader br = null;
    try {//from   w ww . j ava  2  s.co m
        br = new BufferedReader(new FileReader(file));
        String currentLine;

        while ((currentLine = br.readLine()) != null) {
            sb.append(currentLine);
            sb.append('\n');
        }
    } finally {
        if (br != null) {
            br.close();
        }
    }

    return sb.toString();
}

From source file:Main.java

public static String readXmlAsString(File input) throws IOException {
    String xmlString = "";

    if (input == null) {
        throw new IOException("The input stream object is null.");
    }/*from   w  w  w  .  j  a  va  2  s  .  co  m*/

    FileInputStream fileInputStream = new FileInputStream(input);
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    String line = bufferedReader.readLine();
    while (line != null) {
        xmlString += line + "\n";
        line = bufferedReader.readLine();
    }
    fileInputStream.close();
    fileInputStream.close();
    bufferedReader.close();

    return xmlString;
}

From source file:Main.java

public static String readLine(String filename) {
    BufferedReader br = null;
    String line = null;// ww  w  . ja v a2 s . c o  m
    try {
        br = new BufferedReader(new FileReader(filename), 1024);
        line = br.readLine();
    } catch (IOException e) {
        return null;
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return line;
}

From source file:com.abid_mujtaba.bitcoin.tracker.network.Client.java

private static String InputStreamToString(InputStream content) throws ClientException {
    try {/*ww w. j a v  a 2  s .  co  m*/
        BufferedReader br = new BufferedReader(new InputStreamReader(content, "UTF-8"));

        String line;
        StringBuilder sb = new StringBuilder();

        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        br.close();

        return sb.toString();
    } catch (UnsupportedEncodingException e) {
        throw new ClientException("Content InputStream has unsupported encoding.", e);
    } catch (IOException e) {
        throw new ClientException("IOException thrown by BufferedReader while reading InputStream.", e);
    }
}

From source file:com.cloudera.knittingboar.utils.DataUtils.java

public static synchronized File getTwentyNewsGroupDir() throws IOException {
    if (twentyNewsGroups != null) {
        return twentyNewsGroups;
    }/*w  w w.  j  av a  2  s .c o m*/
    // mac gives unique tmp each run and we want to store this persist
    // this data across restarts
    File tmpDir = new File("/tmp");
    if (!tmpDir.isDirectory()) {
        tmpDir = new File(System.getProperty("java.io.tmpdir"));
    }
    File baseDir = new File(tmpDir, TWENTY_NEWS_GROUP_LOCAL_DIR);
    if (!(baseDir.isDirectory() || baseDir.mkdir())) {
        throw new IOException("Could not mkdir " + baseDir);
    }
    File tarFile = new File(baseDir, TWENTY_NEWS_GROUP_TAR_FILE_NAME);

    if (!tarFile.isFile()) {
        FileUtils.copyURLToFile(new URL(TWENTY_NEWS_GROUP_TAR_URL), tarFile);
    }

    Process p = Runtime.getRuntime()
            .exec(String.format("tar -C %s -xvf %s", baseDir.getAbsolutePath(), tarFile.getAbsolutePath()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    System.out.println("Here is the standard error of the command (if any):\n");
    String s;
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
    }
    stdError.close();
    twentyNewsGroups = baseDir;
    return twentyNewsGroups;
}

From source file:com.leosys.core.utils.HttpServiceImpl.java

public static String getZiku(String domin) {
    Properties p = new Properties();
    String urls = getXmlPath();// ww  w.ja  va 2  s  .  co  m
    try {
        p.load(new FileInputStream(urls));
    } catch (Exception e) {
        e.printStackTrace();
    }
    String subUrl = p.getProperty("path");
    String restUrl = subUrl + "model=myservice&action=getwebsiteziku&domain=" + domin + "&pagesize=1000";
    StringBuffer strBuf;
    strBuf = new StringBuffer();

    try {
        URL url = new URL(restUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));//?  
        String line = null;
        while ((line = reader.readLine()) != null)
            strBuf.append(line + " ");
        reader.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(strBuf.toString());

    return strBuf.toString();
}

From source file:org.cmuchimps.gort.modules.webinfoservice.AppEngineUpload.java

private static String uploadBlobstoreDataNoRetry(String url, String filename, String mime, byte[] data) {
    if (url == null || url.length() <= 0) {
        return null;
    }/*from   ww w.  j  av a 2  s . co m*/

    if (data == null || data.length <= 0) {
        return null;
    }

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost httpPost = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("data", new ByteArrayBody(data, mime, filename));

    httpPost.setEntity(entity);

    try {
        HttpResponse response = httpClient.execute(httpPost);

        System.out.println("Blob upload status code: " + response.getStatusLine().getStatusCode());

        /*
        //http://grinder.sourceforge.net/g3/script-javadoc/HTTPClient/HTTPResponse.html
        // 2xx - success
        if (response.getStatusLine().getStatusCode() / 100 != 2) {
            return null;
        }
        */

        InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
        BufferedReader br = new BufferedReader(isr);

        String blobKey = br.readLine();

        blobKey = (blobKey != null) ? blobKey.trim() : null;

        br.close();
        isr.close();

        if (blobKey != null && blobKey.length() > 0) {
            return String.format("%s%s", MTURKSERVER_BLOB_DOWNLOAD_URL, blobKey);
        } else {
            return null;
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.blogspot.ryanfx.auth.GoogleUtil.java

/**
 * Sends the auth token to google and gets the json result.
 * @param token auth token//from  w ww  .  ja v a 2  s.co  m
 * @return json result if valid request, null if invalid.
 * @throws IOException
 * @throws LoginException
 */
private static String issueTokenGetRequest(String token) throws IOException, LoginException {
    int timeout = 2000;
    URL u = new URL("https://www.googleapis.com/oauth2/v2/userinfo");
    HttpURLConnection c = (HttpURLConnection) u.openConnection();
    c.setRequestMethod("GET");
    c.setRequestProperty("Content-length", "0");
    c.setRequestProperty("Authorization", "OAuth " + token);
    c.setUseCaches(false);
    c.setAllowUserInteraction(false);
    c.setConnectTimeout(timeout);
    c.setReadTimeout(timeout);
    c.connect();
    int status = c.getResponseCode();
    if (status == HttpServletResponse.SC_OK) {
        BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        return sb.toString();
    } else if (status == HttpServletResponse.SC_UNAUTHORIZED) {
        Logger.getLogger(GoogleUtil.class.getName()).severe("Invalid token request: " + token);
    }
    return null;
}

From source file:com.thomaskuenneth.openweathermapweather.WeatherUtils.java

public static String getFromServer(String url) throws MalformedURLException, IOException {
    StringBuilder sb = new StringBuilder();
    URL _url = new URL(url);
    HttpURLConnection httpURLConnection = (HttpURLConnection) _url.openConnection();
    String contentType = httpURLConnection.getContentType();
    String charSet = "ISO-8859-1";
    if (contentType != null) {
        Matcher m = PATTERN_CHARSET.matcher(contentType);
        if (m.matches()) {
            charSet = m.group(1);//from   www  .  ja  va2  s . c  om
        }
    }
    final int responseCode = httpURLConnection.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream(),
                charSet);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        try {
            bufferedReader.close();
        } catch (IOException ex) {
            LOGGER.log(Level.SEVERE, "getFromServer()", ex);
        }
    }
    httpURLConnection.disconnect();
    return sb.toString();
}

From source file:Main.java

public static String getHttpClientString(String path) {
    BasicHttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
    HttpClient client = new DefaultHttpClient(httpParams);
    DefaultHttpClient httpClient = (DefaultHttpClient) client;
    HttpResponse httpResponse = null;/*from  w w  w .  j  a  v  a  2 s  .co m*/
    String result = "";
    try {
        httpResponse = httpClient.execute(new HttpGet(path));
        int res = httpResponse.getStatusLine().getStatusCode();
        if (res == 200) {
            InputStream in = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "GBK"));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line.trim());
            }
            reader.close();
            in.close();
            result = sb.toString();
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return result;
}