Android上Assets文件夹中的InputStream返回空

use*_*775 7 java io android assets inputstream

我没有任何例外,但是当我跑...

InputStream deckFile = context.getAssets().open("cards.txt");
Run Code Online (Sandbox Code Playgroud)

然后,deckFile.read()返回-1.该文件位于正确的文件夹中,并且它不为空.

这应该是世界上最简单的事情......

编辑:AssetManager确实列出了"cards.txt",因此不应该是问题.

Har*_*ara 8

尝试下面的代码行

InputStream is = getAssets().open("test.txt");
int size = is.available();
byte[] buffer = new byte[size]; //declare the size of the byte array with size of the file
is.read(buffer); //read file
is.close(); //close file

// Store text file data in the string variable
    String str_data = new String(buffer);
Run Code Online (Sandbox Code Playgroud)

可用方法返回资产的总大小...


GrI*_*sHu 5

将您的文本文件放在/assetsAndroid项目下的目录中.使用AssetManager类来访问它.

AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");
Run Code Online (Sandbox Code Playgroud)

或者您也可以将文件放在/res/raw目录中,文件将被编入索引,并且可以通过R文件中的ID访问:

InputStream is = getResources().openRawResource(R.raw.test);
Run Code Online (Sandbox Code Playgroud)

编辑:

尝试以下方法来读取您的文件:

 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 "";
    }
}
Run Code Online (Sandbox Code Playgroud)

我相信它会对你有所帮助.


use*_*775 3

问题是我的文件太大,并且由于它的扩展名是“.txt”而被压缩。通过将文件重命名为通常压缩的格式“.mp3”,没有问题