1

I've been Googling up some answers, and I can't seem to find the best one.

Here's what I have so far for reading internal files on Android:

        fis = openFileInput("MY_FILE");
        StringBuilder fileContent = new StringBuilder("");
        byte[] buffer = new byte[fis.available()];
        while (fis.read(buffer) != -1) {
            fileContent.append(new String(buffer));
        }
        MYVARIABLE = fileContent.toString();
        fis.close();

It use to leave a lot of whitespaces, but I just used .available method to only return what I need.

Is there a faster or shorter way to write this? I can't seem to find any good ones in the API guide.

4

1 回答 1

1

1). API for available() says it should not be used for the purposes you need:

Note that this method provides such a weak guarantee that it is not very useful in practice.

Meaning it may not give you the file size.

2). When you read smth in RAM, then take under account the file can be lengthy, so try to avoid spending extra RAM. For this a relatively small (1~8 KB) buffer is used to read from source and then append to result. On the other hand using too small buffers (say, several bytes) slows down reading significantly.

3). Reading bytes differs from reading characters, because a single character may be represented by more than one byte (depends on encoding). To read chars the spesific classes are used which are aware of encoding and know how to convert bytes to chars properly. For instance InputStreamReader is one of such classes.

4). The encoding to use for reading should be the encoding tha was used for persisting the data.

Taking all the said above I would use smth like this:

public static String getStringFromStream(InputStream in, String encoding) 
        throws IOException {
    InputStreamReader reader;
    if (encoding == null) {
        // This constructor sets the character converter to the encoding
        // specified in the "file.encoding" property and falls back 
        // to ISO 8859_1 (ISO-Latin-1) if the property doesn't exist.
        reader = new InputStreamReader(in);
    } else {
        reader = new InputStreamReader(in, encoding);
    }

    StringBuilder sb = new StringBuilder();

    final char[] buf = new char[1024];
    int len;
    while ((len = reader.read(buf)) > 0) {
        sb.append(buf, 0, len);
    }

    return sb.toString();
}

5). Make sure to always close an InputStream when done working with it.

Sure, there are more than one way to read text from file in Java/Android. This is mostly because Java API contains several generations of IO APIs. For instance, classes from java.nio package were created to be more efficient, however usually there is no strong reason of using them (don't fall into premature optimization sin).

于 2013-06-28T10:08:43.720 回答