3

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

1) the R.introduced resource

2) some absolute/relative URI

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

Neel
  • 597
  • 6
  • 19

2 Answers2

5

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);
    }
}
Neel
  • 597
  • 6
  • 19
0

some absolute/relative URI

Very few things in Android support that.

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

You don't. A resource does not exist as a file on the filesystem of the Android device. Modify the class to not require a file, but instead take the resource ID, or an XmlResourceParser.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I can move resource.xml anywhere. Is there somewhere that I can put it so I can treat it as a File? – Neel Jan 10 '16 at 18:35
  • @Neal: Nothing that ships with your app automatically becomes a file on the filesystem of the device. You are welcome to package your XML as an asset (e.g., `src/main/assets/` of an Android Studio module), then write some code to copy the asset to a file on [internal storage](https://commonsware.com/blog/2014/04/07/storage-situation-internal-storage.html). That resulting file is a file on the filesystem, and you can use `File` to point to it. – CommonsWare Jan 10 '16 at 18:50