Java – Android reads from a file

Android reads from a file… here is a solution to the problem.

Android reads from a file

I’m new to android and can’t understand the reason for the new assignment in the loop while reading a book. Isn’t it enough to do it once before looping?

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

Solution

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’s no reason to create a new char[] in the loop.

Related Problems and Solutions