mobile/android/base/util/RawResource.java

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/mobile/android/base/util/RawResource.java	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,52 @@
     1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.7 +
     1.8 +package org.mozilla.gecko.util;
     1.9 +
    1.10 +import android.content.Context;
    1.11 +import android.content.res.Resources;
    1.12 +
    1.13 +import java.io.IOException;
    1.14 +import java.io.InputStream;
    1.15 +import java.io.InputStreamReader;
    1.16 +import java.io.StringWriter;
    1.17 +
    1.18 +/**
    1.19 + * {@code RawResource} provides API to load raw resources in different
    1.20 + * forms. For now, we only load them as strings. We're using raw resources
    1.21 + * as localizable 'assets' as opposed to a string that can be directly
    1.22 + * translatable e.g. JSON file vs string.
    1.23 + *
    1.24 + * This is just a utility class to avoid code duplication for the different
    1.25 + * cases where need to read such assets.
    1.26 + */
    1.27 +public final class RawResource {
    1.28 +    public static String getAsString(Context context, int id) throws IOException {
    1.29 +        InputStreamReader reader = null;
    1.30 +
    1.31 +        try {
    1.32 +            final Resources res = context.getResources();
    1.33 +            final InputStream is = res.openRawResource(id);
    1.34 +            if (is == null) {
    1.35 +                return null;
    1.36 +            }
    1.37 +
    1.38 +            reader = new InputStreamReader(is);
    1.39 +
    1.40 +            final char[] buffer = new char[1024];
    1.41 +            final StringWriter s = new StringWriter();
    1.42 +
    1.43 +            int n;
    1.44 +            while ((n = reader.read(buffer, 0, buffer.length)) != -1) {
    1.45 +                s.write(buffer, 0, n);
    1.46 +            }
    1.47 +
    1.48 +            return s.toString();
    1.49 +        } finally {
    1.50 +            if (reader != null) {
    1.51 +                reader.close();
    1.52 +            }
    1.53 +        }
    1.54 +    }
    1.55 +}
    1.56 \ No newline at end of file

mercurial