设为首页 加入收藏

TOP

Android读取Txt文件
2014-11-24 02:29:33 来源: 作者: 【 】 浏览:2
Tags:Android 读取 Txt 文件

1、读取资源文件


资源文件一般放到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;
}
}


2、访问外部存储


访问SD卡上的文件一般需要先判断外部存储空间的状态,如果状态为Environment.MEDIA_MOUNTED,则表示状态正常,然后需要获取根目录名称并对文件进行操作。


示例代码如下:


boolean sdCardExist = Environment.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
if (sdCardExist)
{
File sdDir = Environment.getExternalStorageDirectory();//获取跟目录
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android数据库之SQLiteDatabase类 下一篇仿照Linux下的U-Boot来DIY自己的a..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: