android读取assets中的txt文件路径,Android-通过file:///android_asset/test.txt路径获取不到文件...

这篇博客介绍了在Android应用中如何从assets目录读取文件并保存到SD卡的临时文件中,同时展示了使用FileOutputStream和InputStream进行文件操作的过程。在程序结束时,临时文件会被删除以释放存储空间。作者还提出了一个问题,关于使用getClass().getClassLoader().getResourceAsStream()方法无法成功读取文件,希望得到解答。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我自己的一种做法,结合了wide_n以及网上一些其他人的提供的资料:

InputStream is;

tmpFile = new File(getExternalFilesDir(null), "100ss_l.png"); //该路径指向SD卡目录下一个特定文件夹,需要在uses-permission设置WRITE-EXTERNAL-STORAGE权限

Log.w("File", "File path is: " + path);

try {

is = getClass().getResourceAsStream("/assets/www/images/100ss_l.png");

if(!tmpFile.exists()){

FileOutputStream fos = new FileOutputStream(tmpFile);

byte[] buffer = new byte[400000];

int count = 0;

while ((count = is.read(buffer)) > 0) {

fos.write(buffer, 0, count);

}

fos.close();

}

is.close();

} catch (IOException e) {

Log.w("ExternalStorage", "Error writing " + tmpFile, e);

e.printStackTrace();

}

Uri uri = Uri.fromFile(tmpFile);

Log.w("Uri", "Uri path is: " + uri);

uris.add(uri);

图片被输出到一个临时文件中,在程序结束时可以删除文件:

@Override

protected void onDestroy(){

super.onDestroy();

//delete temp file

if(tmpFile.exists())

tmpFile.delete();

}

顺便请教一下各位高手:

我见过一些程序写法如下:

getClass().getClassLoader().getResourceAsStream("/assets/www/images/100ss_l.png");

这里的getClassLoader()方法有什么作用呢?包括API DOC里也是推荐要加。但我加上这个反而取不到文件了。哪位了解的请指点一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值