如何按名称从 res/raw 读取文件

问题描述 投票:0回答:5

我想打开文件夹 res/raw/ 中的文件。 我绝对确定该文件存在。 打开我尝试过的文件

File ddd = new File("res/raw/example.png");

命令

ddd.exists(); 

产生FALSE。所以这个方法行不通。

尝试

MyContext.getAssets().open("example.png");

最终出现 getMessage()“null”异常。

简单使用

R.raw.example

这是不可能的,因为文件名仅在运行时作为字符串被识别。

为什么访问 /res/raw/ 文件夹中的文件这么困难?

android file-io resources
5个回答
180
投票

在给定链接的帮助下,我能够自己解决问题。正确的方法是通过

获取资源ID
getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
                             "raw", getPackageName());

将其作为输入流

InputStream ins = getResources().openRawResource(
            getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
            "raw", getPackageName()));

52
投票

以下是从原始文件夹中获取 XML 文件的示例:

 InputStream XmlFileInputStream = getResources().openRawResource(R.raw.taskslists5items); // getting XML

然后你可以:

 String sxml = readTextFile(XmlFileInputStream);

何时:

 public String readTextFile(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {

        }
        return outputStream.toString();
    }

15
投票

您可以使用

getResources().openRawResource(R.raw.myfilename)
读取 raw/res 中的文件。

但是 IDE 有一个限制,您使用的文件名只能包含小写字母数字字符和点。因此像

XYZ.txt
my_data.bin
这样的文件名不会在 R 中列出。


5
投票

您可以通过以下两种方法使用 Kotlin 读取原始资源。

通过获取资源id即可获取。或者,您可以使用字符串标识符,您可以在其中以编程方式增量更改文件名。

干杯伙计🎉

// R.raw.data_post

this.context.resources.openRawResource(R.raw.data_post)
this.context.resources.getIdentifier("data_post", "raw", this.context.packageName)

0
投票

我们需要传递原始文件id并打开和关闭输入流来转换原始资源。

import android.content.Context;
import android.content.res.Resources;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileUtils {
    public static File getFileFromRaw(Context context, int resId, String fileName) {
        Resources resources = context.getResources();
        File file = null;
        try {
            // Open the audio file from the raw folder
            InputStream inputStream = resources.openRawResource(resId);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            inputStream.close();

            // Create a new File Object
            file = new File(context.getExternalFilesDir(null), fileName);
            FileOutputStream outputStream = new FileOutputStream(file);
            outputStream.write(bytes);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
}

然后像这样使用它

File audioFile = FileUtils.getFileFromRaw(this, R.raw.rain_drops, "rain_drops.m4a");
© www.soinside.com 2019 - 2024. All rights reserved.