你好,游客 登录 注册 搜索
背景:
阅读新闻

Android读取Txt文件

[日期:2013-11-20] 来源:Linux社区  作者:Linux [字体:大 中 小]

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读取SD卡下面所有的TXT文件名 listView显示出来 http://www.linuxidc.com/Linux/2011-12/49966.htm

更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11

linux
相关资讯       Android读取Txt  Android文件读取 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款