0

I am reading the contents of buffered reader in the below method:

public static String readBuffer(Reader reader, int limit) throws IOException 
{           
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < limit; i++) {
        int c = reader.read();
            if (c == -1) {
                return ((sb.length() > 0) ? sb.toString() : null);
            }
        if (((char) c == '\n') || ((char) c == '\r')) {
            break;
    }
        sb.append((char) c);
}
    return sb.toString();
}   

I am invoking this method later to test -

URL url = new URL("http://www.oracle.com/");
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));        
    StringBuffer sb = new StringBuffer();
    String line=null;
    while((line=readBuffer(in, 2048))!=null) {
        sb.append(line);
    }
    System.out.println(sb.toString());

My question here is, I am returning the contents of bufferedreader into a string in my first method, and appending these String contents into a StringBuffer again in the second method, and reading out of it. Is this the right way? Any other way I can read the String contents that has contents from url?Please advise.

rickygrimes
  • 2,637
  • 9
  • 46
  • 69
  • Is there anything wrong with [`BufferedReader#readLine`](http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine())? – MadProgrammer Mar 28 '14 at 06:17
  • possible duplicate of [Reading website's contents into string](http://stackoverflow.com/questions/5867975/reading-websites-contents-into-string) –  Mar 28 '14 at 06:24
  • No its not a duplicate. – rickygrimes Mar 28 '14 at 06:26
  • @RC - Please read the question before marking it a duplicate, and voting for closing it! – rickygrimes Mar 28 '14 at 06:34
  • @rickygrimes I do what I want with my votes. I think it's a duplicate and you don't (that's your right). That's probably why a question need 5 votes to be *closed as duplicate* –  Mar 28 '14 at 06:47

1 Answers1

0

I hope this works -

public static String readFromURL(){
    URL url = new URL("http://www.oracle.com/");
    StringBuilder responseBuilder = new StringBuilder();
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setDoInput(true);

    int resCode = httpCon.getResponseCode();
    InputStream is = null;
    if (resCode == 200) {
         is = httpCon.getInputStream();
         BufferedReader reader = new BufferedReader(
                 new InputStreamReader(is));
         String response = null;
         while (true) {
             response = reader.readLine();
             if (response == null)
                 break;
             responseBuilder.append(response);
         }
    }
    return responseBuilder.toString();
}

hellboy
  • 2,222
  • 1
  • 14
  • 19