您的位置:首页 > 移动开发 > Android开发

android读取资源文件的方法

2013-07-27 17:01 633 查看
方法一:把目标文件放入resources文件中,以通过读取R的资源文件来获取,具体方式如下:

1、在res下新建raw文件,将带读取文件添加到raw文件目录下。

2、添加如下代码:

// 如果要使用文件名获取文件数据:首先获取资源id然后再通过id获取输入流

/** String fileName = fileName;

String packetName = context.getPackageName();

//将fileName 转换成id

int resId = context.getResources().getIdentifier(fileName, "raw", packetName);

ObjectInputStream ois = null;

InputStream im = context.getResources().openRawResource(resId);

//其中getIdentifier三参数分别是:文件名,资源所在文件夹名(如:drawable, raw,),包路径

*/

InputStream im = getResources().openRawResource(R.raw.h_data11);

BufferedReader read = new BufferedReader(new InputStreamReader(im));

String line = "";

StringBuilder sb = new StringBuilder();

try {

while((line = read.readLine()) != null) {

sb.append(line).append("\n");

}

} catch (IOException e) {

e.printStackTrace();

} finally {

if(read != null) {

try {

read.close();

read = null;

} catch (IOException e) {

e.printStackTrace();

}

}

if(im != null) {

try {

im.close();

im = null;

} catch (IOException e) {

e.printStackTrace();

}

}

}

Log.v("", "result = " + sb.toString());

复制代码
方法二:使用assets 只读文件进行读取。

1、将文件copy到assets下,可以新建文件夹如:“www”然后将文件放入www文件夹中,读取的path为:"www/filename"

String result = "";

ObjectInputStream ois = null;

AssetManager am = context.getResources().getAssets();

try {

ois = new ObjectInputStream(am.open("www/filename"));

result = (String) ois.readObject();

} catch (StreamCorruptedException e) {

e.printStackTrace();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} catch (ClassNotFoundException e) {

e.printStackTrace();

} finally {

try {

if (ois != null) {

ois.close();

ois = null;

}

} catch (IOException e) {

e.printStackTrace();

}

}

复制代码
以对象的方式读取文件中的数据,如果没有新建文件夹,把前面的“www/”去掉就ok啦
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: