簡體   English   中英

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

[英]InputStream from Assets folder on Android returning empty

我沒有任何例外,但是當我跑...

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

然后,deckFile.read()返回-1。 該文件位於正確的文件夾中,並且它不為空。

這應該是世界上最簡單的事情......

編輯:AssetManager確實列出了“cards.txt”,因此不應該是問題。

嘗試下面的代碼行

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);

可用方法返回資產的總大小...

將您的文本文件放在Android項目下的/assets目錄中。 使用AssetManager類來訪問它。

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

或者您也可以將文件放在/res/raw目錄中,該文件將被索引,並且可以通過R文件中的id訪問:

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

編輯:

嘗試以下方法來讀取您的文件:

  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 ""; } } 

我相信它會對你有所幫助。

問題是我的文件太大了,因為它是“.txt”擴展名而被壓縮了。 通過將文件重命名為通常壓縮的格式“.mp3”,沒有問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM