从资源创建文件对象 [英] Creating a File object from a resource

查看:82
本文介绍了从资源创建文件对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在/res/introduced.xml中有一个文件.我知道我可以通过两种方式访问​​它:

I have a file located at /res/introduced.xml. I know that I can access it in two ways:

1)R.引入的资源

2)一些绝对/相对URI

2) some absolute/relative URI

我正在尝试创建一个File对象,以将其传递给特定的类.我该怎么办?

I'm trying to create a File object in order to pass it to a particular class. How do I do that?

推荐答案

这就是我最后要做的事情:

This is what I ended up doing:

try{
  InputStream inputStream = getResources().openRawResource(R.raw.some_file);
  File tempFile = File.createTempFile("pre", "suf");
  copyFile(inputStream, new FileOutputStream(tempFile));

  // Now some_file is tempFile .. do what you like
} catch (IOException e) {
  throw new RuntimeException("Can't create temp file ", e);
}

private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}

这篇关于从资源创建文件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆