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