Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android reading from a file

Tags:

java

android

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];
        }
like image 427
Leon Avatar asked Dec 05 '25 14:12

Leon


2 Answers

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.

like image 179
ben75 Avatar answered Dec 07 '25 02:12

ben75


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.

like image 20
Vladimir Mironov Avatar answered Dec 07 '25 02:12

Vladimir Mironov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!