Leon
Leon

Reputation: 37

android reading from a file

I'm new to android and while reading a book can't understand the reason for new allocation in the loop. Isn't it enough to make it once before the loop?

        FileInputStream fIn =
                openFileInput("textfile.txt");
        InputStreamReader isr = new
                InputStreamReader(fIn);
        char[] inputBuffer = new char[READ_BLOCK_SIZE];
        String s = "";
        int charRead;
        while ((charRead = isr.read(inputBuffer))>0)
        {
            //---convert the chars to a String---
            String readString =
            String.copyValueOf(inputBuffer, 0,
            charRead);
            s += readString;
            inputBuffer = new char[READ_BLOCK_SIZE];
        }

Upvotes: 3

Views: 730

Answers (2)

ben75
ben75

Reputation: 28746

From String.copyValueOf javadoc :

  /**
 * Creates a new string containing the specified characters in the character
 * array. Modifying the character array after creating the string has no
 * effect on the string.
 *
 * @param start
 *            the starting offset in the character array.
 * @param length
 *            the number of characters to use.

So there is no reason to create a new char[] in the loop.

Upvotes: 3

Vladimir Mironov
Vladimir Mironov

Reputation: 30884

It's enough to allocate the buffer only once so you can just remove the allocation inside the loop and it should work well.

And another thing... This code has a really poor performance because it uses string concatenation in the loop. You should use StringBuilder.append() instead of s += readString.

P.S. I would recommend you to choose another book because this one has too many errors in such simple code.

Upvotes: 1

Related Questions