Android读取Txt文件
2013-11-20 09:22
429 查看
读取资源文件
资源文件一般放到assets目录下,读取方法如下:
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetsManager.open("dir/filename.text");
示例代码如下:
访问外部存储
访问SD卡上的文件一般需要先判断外部存储空间的状态,如果状态为Environment.MEDIA_MOUNTED,则表示状态正常,然后需要获取根目录名称并对文件进行操作。
示例代码如下:
资源文件一般放到assets目录下,读取方法如下:
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetsManager.open("dir/filename.text");
示例代码如下:
package com.example.assetstest; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import android.os.Bundle; import android.app.Activity; import android.content.res.AssetManager; import android.view.Menu; import android.widget.TextView; public class AssetsTest extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_assets_test); TextView textView = (TextView)findViewById(R.id.textView); AssetManager assetManager = getAssets(); InputStream inputStream = null; try { inputStream = assetManager.open("text/text.txt"); String text = loadTextFile(inputStream); textView.setText(text); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private String loadTextFile(InputStream inputStream) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] bytes = new byte[4096]; int len = 0; while ((len = inputStream.read(bytes)) > 0) { byteArrayOutputStream.write(bytes, 0, len); } return new String(byteArrayOutputStream.toByteArray(), "UTF8"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.assets_test, menu); return true; } }
访问外部存储
访问SD卡上的文件一般需要先判断外部存储空间的状态,如果状态为Environment.MEDIA_MOUNTED,则表示状态正常,然后需要获取根目录名称并对文件进行操作。
示例代码如下:
boolean sdCardExist = Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在 if (sdCardExist) { File sdDir = Environment.getExternalStorageDirectory();//获取跟目录 }
相关文章推荐
- Android对本地txt的文件读取
- android 读取TXT文件
- Android读取本地TXT文件
- android解决读取assets文件夹下的json或txt文件乱码问题
- Android 读取工程中的txt文件
- android 读取SD卡下TXT文件
- Android 读取assets文件下的txt文件
- android 随手记--读取sd卡txt文件
- android从raw里面读取txt文件
- android 3d游戏研究(二)(边学边写,多谢高手指正,鞠躬) :txt文件读取
- android 读取assets文件下的txt文件
- android txt文件读写(读取资源文件,读取私有和SD文件的方法)
- android-读取本地txt文件 - 随心
- Android读取txt文本文件
- android-解决读取txt文件中文乱码问题
- 【string编码格式】Android读取txt文件乱码问题
- Android 读取本地txt文件中的内容
- android txt文件读写(读取资源文件,读取私有和SD文件的方法)
- 基于android中读取assets目录下a.txt文件并进行解析的深入分析
- Android保存读取txt文件