mobile/android/base/util/RawResource.java

Thu, 22 Jan 2015 13:21:57 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Thu, 22 Jan 2015 13:21:57 +0100
branch
TOR_BUG_9701
changeset 15
b8a032363ba2
permissions
-rw-r--r--

Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6

     1 /* This Source Code Form is subject to the terms of the Mozilla Public
     2  * License, v. 2.0. If a copy of the MPL was not distributed with this
     3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     5 package org.mozilla.gecko.util;
     7 import android.content.Context;
     8 import android.content.res.Resources;
    10 import java.io.IOException;
    11 import java.io.InputStream;
    12 import java.io.InputStreamReader;
    13 import java.io.StringWriter;
    15 /**
    16  * {@code RawResource} provides API to load raw resources in different
    17  * forms. For now, we only load them as strings. We're using raw resources
    18  * as localizable 'assets' as opposed to a string that can be directly
    19  * translatable e.g. JSON file vs string.
    20  *
    21  * This is just a utility class to avoid code duplication for the different
    22  * cases where need to read such assets.
    23  */
    24 public final class RawResource {
    25     public static String getAsString(Context context, int id) throws IOException {
    26         InputStreamReader reader = null;
    28         try {
    29             final Resources res = context.getResources();
    30             final InputStream is = res.openRawResource(id);
    31             if (is == null) {
    32                 return null;
    33             }
    35             reader = new InputStreamReader(is);
    37             final char[] buffer = new char[1024];
    38             final StringWriter s = new StringWriter();
    40             int n;
    41             while ((n = reader.read(buffer, 0, buffer.length)) != -1) {
    42                 s.write(buffer, 0, n);
    43             }
    45             return s.toString();
    46         } finally {
    47             if (reader != null) {
    48                 reader.close();
    49             }
    50         }
    51     }
    52 }

mercurial