0

I am reading an HTML file and saving it in a string. I wanted to read the length (int len = con.getcontentlength()) and put char charArray=new char(len) but the result of getContentLength is always -1. So I fix the charArray but if I put char[] charArray=new char[1] or char[] charArray=new char[512] or char[] charArray=new char[1024]

it always works.

I don't understand why.

public static void main(String[] args) throws Exception
{
    String name="AAAA";     
    URL url = new URL("http:...");
    URLConnection con = url.openConnection();

    InputStream is = con.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);

    int numCharsRead;   
    char[] charArray = new char[1];
    StringBuffer sb = new StringBuffer();
    while ((numCharsRead = isr.read(charArray)) > 0)
        sb.append(charArray, 0, numCharsRead);
    String htmlString = sb.toString();
2
  • don't use StringBuffer unless your program is multithreading. use StringBuilder instead. Commented Jan 16, 2013 at 9:57
  • Ok thx i changed to Stringbuilder but the charArray ? i can put the dimension i want Commented Jan 16, 2013 at 10:03

2 Answers 2

3

Change from new char[1]; to new char[isr.available()];

Sign up to request clarification or add additional context in comments.

Comments

0
InputStreamReader isr = new InputStreamReader(is);
    int c = 0;
    while((c = isr.read()) != -1) {
        char character = (char) c;

        System.out.println(character);

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.