android 如何读取 assets、raws文件

2025-10-24 22:33:20

1、读输入流的方法:通过读输入流返回一个String

/**

 * 读输入流

 * 

 * @param is

 * @return

 */

public static String getStringByInputStream(InputStream is) {

String content = null;

try {

if (is != null) {

byte[] buffer = new byte[is.available()];

ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();

while (true) {

int readLength = is.read(buffer);

if (readLength == -1)

break;

arrayOutputStream.write(buffer, 0, readLength);

}

is.close();

arrayOutputStream.close();

content = new String(arrayOutputStream.toByteArray());

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

content = null;

} finally {

try {

if (is != null)

is.close();

} catch (IOException ioe) {

ioe.printStackTrace();

}

}

return content;

}

2、读assets文件的方法:

public static String readAssets(Context context, String fileName) {

InputStream is = null;

try {

is = context.getAssets().open(fileName);

} catch (IOException e) {

e.printStackTrace();

}

return getStringByInputStream(is);

}

3、读raw文件的方法:

public static String readRaws(Context context, int id) {

InputStream is = context.getResources().openRawResource(id);

return getStringByInputStream(is);

}

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢