从资源创建文件对象
Creating a File object from a resource
我有一个位于 /res/introduced.xml 的文件。我知道我可以通过两种方式访问它:
1) R.introduced 资源
2) 一些 absolute/relative URI
我正在尝试创建一个文件对象,以便将其传递给特定的 class。我该怎么做?
some absolute/relative URI
Android 中很少有东西支持这一点。
I'm trying to create a File object in order to pass it to a particular class. How do I do that?
你不知道。资源在 Android 设备的文件系统上不作为文件存在。将 class 修改为不需要文件,而是获取资源 ID,或 XmlResourceParser
.
这就是我最后做的事情:
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);
}
}
我有一个位于 /res/introduced.xml 的文件。我知道我可以通过两种方式访问它:
1) R.introduced 资源
2) 一些 absolute/relative URI
我正在尝试创建一个文件对象,以便将其传递给特定的 class。我该怎么做?
some absolute/relative URI
Android 中很少有东西支持这一点。
I'm trying to create a File object in order to pass it to a particular class. How do I do that?
你不知道。资源在 Android 设备的文件系统上不作为文件存在。将 class 修改为不需要文件,而是获取资源 ID,或 XmlResourceParser
.
这就是我最后做的事情:
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);
}
}