【问题标题】:Creating a File object from a resource从资源创建文件对象
【发布时间】:2016-01-10 18:29:39
【问题描述】:

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

1) R.introduced 资源

2) 一些绝对/相对 URI

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

【问题讨论】:

    标签: android file resources uri


    【解决方案1】:

    这就是我最终做的:

    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);
        }
    }
    

    【讨论】:

    • 这是最好的解决方案,你拯救了我的一天,非常感谢!
    【解决方案2】:

    一些绝对/相对 URI

    Android 中很少有东西支持这一点。

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

    你没有。资源不作为文件存在于 Android 设备的文件系统中。将类修改为不需要文件,而是使用资源 ID 或 XmlResourceParser

    【讨论】:

    • 我可以将 resource.xml 移动到任何地方。有什么地方可以放它,以便我可以将其视为文件?
    • @Neal:您的应用程序附带的任何内容都不会自动成为设备文件系统上的文件。欢迎您将 XML 打包为资产(例如,Android Studio 模块的src/main/assets/),然后编写一些代码将资产复制到internal storage 上的文件中。生成的文件是文件系统上的一个文件,您可以使用File 指向它。
    猜你喜欢
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 2012-12-18
    • 2023-02-04
    • 1970-01-01
    相关资源
    最近更新 更多