简体   繁体   中英

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];
        }

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM