InputStream from Assets folder on Android returning empty

后端 未结 3 1726
盖世英雄少女心
盖世英雄少女心 2021-01-02 15:04

I\'m not getting any exceptions, but when I run...

InputStream deckFile = context.getAssets().open(\"cards.txt\");

Then, deckFile.read() r

3条回答
  •  清酒与你
    2021-01-02 15:26

    Place your text file in the /assets directory under the Android project. Use AssetManager class to access it.

    AssetManager am = context.getAssets();
    InputStream is = am.open("test.txt");
    

    Or you can also put the file in the /res/raw directory, where the file will be indexed and is accessible by an id in the R file:

    InputStream is = getResources().openRawResource(R.raw.test);
    

    EDITED:

    Try out the below method to read your file:

     public String convertStreamToString(InputStream p_is) throws IOException {
        /*
         * To convert the InputStream to String we use the
         * BufferedReader.readLine() method. We iterate until the BufferedReader
         * return null which means there's no more data to read. Each line will
         * appended to a StringBuilder and returned as String.
         */
        if (p_is != null) {
            StringBuilder m_sb = new StringBuilder();
            String m_line;
            try {
                BufferedReader m_reader = new BufferedReader(
                        new InputStreamReader(p_is));
                while ((m_line = m_reader.readLine()) != null) {
                    m_sb.append(m_line).append("\n");
                }
            } finally {
                p_is.close();
            }
            Log.e("TAG", m_sb.toString());
            return m_sb.toString();
        } else {
            return "";
        }
    }
    

    I am sure it will help you.

提交回复
热议问题