michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: package org.mozilla.gecko.util; michael@0: michael@0: import android.content.Context; michael@0: import android.content.res.Resources; michael@0: michael@0: import java.io.IOException; michael@0: import java.io.InputStream; michael@0: import java.io.InputStreamReader; michael@0: import java.io.StringWriter; michael@0: michael@0: /** michael@0: * {@code RawResource} provides API to load raw resources in different michael@0: * forms. For now, we only load them as strings. We're using raw resources michael@0: * as localizable 'assets' as opposed to a string that can be directly michael@0: * translatable e.g. JSON file vs string. michael@0: * michael@0: * This is just a utility class to avoid code duplication for the different michael@0: * cases where need to read such assets. michael@0: */ michael@0: public final class RawResource { michael@0: public static String getAsString(Context context, int id) throws IOException { michael@0: InputStreamReader reader = null; michael@0: michael@0: try { michael@0: final Resources res = context.getResources(); michael@0: final InputStream is = res.openRawResource(id); michael@0: if (is == null) { michael@0: return null; michael@0: } michael@0: michael@0: reader = new InputStreamReader(is); michael@0: michael@0: final char[] buffer = new char[1024]; michael@0: final StringWriter s = new StringWriter(); michael@0: michael@0: int n; michael@0: while ((n = reader.read(buffer, 0, buffer.length)) != -1) { michael@0: s.write(buffer, 0, n); michael@0: } michael@0: michael@0: return s.toString(); michael@0: } finally { michael@0: if (reader != null) { michael@0: reader.close(); michael@0: } michael@0: } michael@0: } michael@0: }