reading a textfile from r.raw on android

纵饮孤独 提交于 2020-01-05 07:25:11

问题


I've got a json file in R.raw.test123,

I need to process that with GSON.

Step one is; read the text into a string, I want to do that using;

BufferedReader r = new BufferedReader(new FileReader(file));

The FileReader expects a string as filename, but how do I turn R.raw.test123 into a string which I can pass to the FileReader.

I've googled for about 4 hours on this, still can't find it. And I know its probally a noob question, but I'm new to droid programming, I come from a .net background, so this is all very new to me...

Thanks,

Dennis


回答1:


As answered by hooked82 you can use get the inputstream with:

InputStream stream = getResources().openRawResource(R.raw.test123);

and then using method to convert it into string:

private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append((line + "\n"));
        }
    } catch (IOException e) {
        Log.w("LOG", e.getMessage());
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            Log.w("LOG", e.getMessage());
        }
    }
    return sb.toString();
}

So you can get the string with convertStreamToString(stream);.




回答2:


How about doing the following:

InputStream stream = getResources().openRawResource(R.raw.test123);


来源:https://stackoverflow.com/questions/6953378/reading-a-textfile-from-r-raw-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!