1. 程式人生 > >Android 讀取res檔案中raw的json檔案 的工具類StreamUtils

Android 讀取res檔案中raw的json檔案 的工具類StreamUtils

public class StreamUtils {
	
	public static String get(Context context, int id) {
		InputStream stream = context.getResources().openRawResource(id);
		return read(stream);
	}
	
	public static String read(InputStream stream) {
		return read(stream, "utf-8");
	}
	
	public static String read(InputStream is, String encode) {
        if (is != null) {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, encode));
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                return sb.toString();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
}

用法:

String data = StreamUtils.get(APP.getInstance(), R.raw.update);