2015-05-18

[Android] 讀取放在專案內的assets資料夾中的檔案到一個String變數當中. Read files in assets to String



If we have a file named "licenses.html" under [your project]/src/main/assets/ ,
you can use the following function to read its content to a String.

String readLicensesHtml() {
    StringBuilder buf = new StringBuilder();
    InputStream stream;
    BufferedReader in;
    String str;
    try {
        stream = getAssets().open("licenses.html");
        in = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        while ((str = in.readLine()) != null) {
            buf.append(str);
        }
        in.close();
    } catch (IOException ignored) {
        Log.e(DEBUG_TAG, ignored.getMessage(), ignored);
    }
    return buf.toString();
}