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",因此不应该是问题.
尝试下面的代码行
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)
可用方法返回资产的总大小...
将您的文本文件放在/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)
编辑:
尝试以下方法来读取您的文件:
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 ""; } }
我相信它会对你有所帮助.
| 归档时间: |
|
| 查看次数: |
22293 次 |
| 最近记录: |