mobile/android/base/util/RawResource.java

changeset 0
6474c204b198
equal deleted inserted replaced
-1:000000000000 0:9cec4e0a18ce
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/. */
4
5 package org.mozilla.gecko.util;
6
7 import android.content.Context;
8 import android.content.res.Resources;
9
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.InputStreamReader;
13 import java.io.StringWriter;
14
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;
27
28 try {
29 final Resources res = context.getResources();
30 final InputStream is = res.openRawResource(id);
31 if (is == null) {
32 return null;
33 }
34
35 reader = new InputStreamReader(is);
36
37 final char[] buffer = new char[1024];
38 final StringWriter s = new StringWriter();
39
40 int n;
41 while ((n = reader.read(buffer, 0, buffer.length)) != -1) {
42 s.write(buffer, 0, n);
43 }
44
45 return s.toString();
46 } finally {
47 if (reader != null) {
48 reader.close();
49 }
50 }
51 }
52 }

mercurial