3

am loading xml file from Assets folder. am getting OutOfMemoryError. The code which i have used is

private String convertStreamToString(InputStream is) {  
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + NEW_LINE);
        }
        reader.close();

    } catch (IOException e) {
        //do nothing.
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            //do nothing.    
        }
    }
    reader=null;
    return sb.toString();
}

Is there an alternate way to get rid of this Exception. It will be more helpful if you post any code. Thanks in advance.

1
  • You may read one line from the XML file, process it, and continue to the next line. Don't read the whole file into memory, the file may be very large. Commented Dec 4, 2012 at 6:47

3 Answers 3

3

It's not a good idea to parse a big Xml using a String. You should turn to a streaming version of the parser. Google Http Java Client proposes such a library : http://code.google.com/p/google-http-java-client

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

Comments

0

put line=null; in while loop after appending to sb.

1 Comment

and sorry to put this as answer because i can not comment at other's post.
0

try Below

Have you tried the built in method to convert a stream to a string? It's part of the Apache Commons library (org.apache.commons.io.IOUtils).

Then your code would be this one line:

String total = IOUtils.toString(inputStream);

The documentation for it can be found here: http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#toString%28java.io.InputStream%29

The Apache Commons IO library can be downloaded from here: http://commons.apache.org/io/download_io.cgi

2 Comments

Can you guide me how to use this one? am little bit confused.
you have to Add External Library

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.