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

Android从raw、assets、SD卡中获取资源文件内容

2013-08-26 20:16 435 查看
先顺带提一下,raw文件夹中的文件会和project一起经过编译,而assets里面的文件不会~~~

另外,SD卡获取文件需要权限哦!

//从res文件夹中的raw 文件夹中获取文件并读取数据

public String getFromRaw(){

String result = "";

try {

InputStream in = getResources().openRawResource(R.raw.data);

//获取文件的字节数

int lenght = in.available();

//创建byte数组

byte[] buffer = new byte[lenght];

//将文件中的数据读到byte数组中

in.read(buffer);

result = EncodingUtils.getString(buffer, "UTF-8");

} catch (Exception e) {

e.printStackTrace();

}

return result;

}

//从assets 文件夹中获取文件并读取数据

public String getFromAssets(String fileName){

String result = "";

try {

InputStream in = getResources().getAssets().open(fileName);

//获取文件的字节数

int lenght = in.available();

//创建byte数组

byte[] buffer = new byte[lenght];

//将文件中的数据读到byte数组中

in.read(buffer);

result = EncodingUtils.getString(buffer, "UTF-8");

} catch (Exception e) {

e.printStackTrace();

}

return result;

}

//从SD卡文件夹中获取文件并读取数据

public static String readFileAsString(String filePath) throws IOException {

File f=null;

f= new File(filePath);//这是对应文件路径全名

StringBuffer fileData = new StringBuffer();

InputStream in = null;

try {

in = new BufferedInputStream(new FileInputStream(f));

} catch (FileNotFoundException e3) {

e3.printStackTrace();

}

BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));

char[] buf = new char[1024];

int numRead=0;

while((numRead=reader.read(buf)) != -1){

String readData = String.valueOf(buf, 0, numRead);

fileData.append(readData);

}

reader.close();

return fileData.toString();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: