How can I read a text file in Android?

前端 未结 7 1494
-上瘾入骨i
-上瘾入骨i 2020-11-22 07:51

I want to read the text from a text file. In the code below, an exception occurs (that means it goes to the catch block). I put the text file in the applicati

7条回答
  •  误落风尘
    2020-11-22 08:42

    First you store your text file in to raw folder.

    private void loadWords() throws IOException {
        Log.d(TAG, "Loading words...");
        final Resources resources = mHelperContext.getResources();
        InputStream inputStream = resources.openRawResource(R.raw.definitions);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    
        try {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] strings = TextUtils.split(line, "-");
                if (strings.length < 2)
                    continue;
                long id = addWord(strings[0].trim(), strings[1].trim());
                if (id < 0) {
                    Log.e(TAG, "unable to add word: " + strings[0].trim());
                }
            }
        } finally {
            reader.close();
        }
        Log.d(TAG, "DONE loading words.");
    }
    

提交回复
热议问题