简体   繁体   English

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

[英]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. 然后,deckFile.read()返回-1。 The file is in the correct folder, and it is NOT empty. 该文件位于正确的文件夹中,并且它不为空。

This should be the easiest thing in the world... 这应该是世界上最简单的事情......

EDIT: The AssetManager is indeed listing "cards.txt" as being there, so that shouldn't be the problem. 编辑:AssetManager确实列出了“cards.txt”,因此不应该是问题。

try below line of code 尝试下面的代码行

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

the available method returns the total size of the asset... 可用方法返回资产的总大小...

Place your text file in the /assets directory under the Android project. 将您的文本文件放在Android项目下的/assets目录中。 Use AssetManager class to access it. 使用AssetManager类来访问它。

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: 或者您也可以将文件放在/res/raw目录中,该文件将被索引,并且可以通过R文件中的id访问:

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. 我相信它会对你有所帮助。

The problem was that my file was too big, and was being compressed because of it's ".txt" extension. 问题是我的文件太大了,因为它是“.txt”扩展名而被压缩了。 By renaming the file to a format that is normally compressed, ".mp3", there was no issue 通过将文件重命名为通常压缩的格式“.mp3”,没有问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM