Skip to content Skip to sidebar Skip to footer

Inputstream From Assets Folder On Android Returning Empty

I'm not getting any exceptions, but when I run... InputStream deckFile = context.getAssets().open('cards.txt'); Then, deckFile.read() returns -1. The file is in the correct folde

Solution 1:

try below line of code

InputStream is = getAssets().open("test.txt");
int size = is.available();
byte[] buffer = newbyte[size]; //declare the size of the byte array with size of the fileis.read(buffer); //read fileis.close(); //close file// Store text file data in the string variable
    String str_data = new String(buffer);

the available method returns the total size of the asset...

Solution 2:

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

AssetManageram= context.getAssets();
InputStreamis= 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) {
        StringBuilderm_sb=newStringBuilder();
        String m_line;
        try {
            BufferedReaderm_reader=newBufferedReader(
                    newInputStreamReader(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.

Solution 3:

The problem was that my file was too big, and was being compressed because of it's ".txt" extension. By renaming the file to a format that is normally compressed, ".mp3", there was no issue

Post a Comment for "Inputstream From Assets Folder On Android Returning Empty"