android - 在 Android 中将 Assets 或原始或资源文件作为 File 对象读取

标签 android file-handling android-resources

我有一个 jar 文件,我需要为其传递文件对象。我如何将资源或 Assets 作为文件对象传递给该方法?

如何将项目文件夹中的 Assets 或原始文件转换为文件对象?

最佳答案

这是我做的:

将您的 Assets 文件复制到 SDCard 中:

AssetManager assetManager = context.getResources().getAssets();

String[] files = null;

try {
    files = assetManager.list("ringtone"); //ringtone is folder name
} catch (Exception e) {
    Log.e(LOG_TAG, "ERROR: " + e.toString());
}

for (int i = 0; i < files.length; i++) {
    InputStream in = null;
    OutputStream out = null;
    try {
        in = assetManager.open("ringtone/" + files[i]);
        out = new FileOutputStream(basepath + "/ringtone/" + files[i]);

        byte[] buffer = new byte[65536 * 2];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
        Log.d(LOG_TAG, "Ringtone File Copied in SD Card");
    } catch (Exception e) {
        Log.e(LOG_TAG, "ERROR: " + e.toString());
    }
}

然后通过路径读取你的文件:

File ringFile = new File(Environment.getExternalStorageDirectory().toString() + "/ringtone", "fileName.mp3");

给你。您有 Assets 文件的文件对象的副本。希望这会有所帮助。

关于android - 在 Android 中将 Assets 或原始或资源文件作为 File 对象读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10930716/

相关文章:

python - 在Python中读取具有大量列的文件

java - 可变地访问资源 "R.string"

android - 在android中存储配置

java - 从任意类获取Android资源值

python - Kivy Plyer通知

android - 拉伸(stretch)图片的一部分,而不是整个(9patch)

写入文件的 C 代码无法编译

java - Android中从本地隐藏文件夹下载图像并显示

android - 在Android中,Matrix类的mapRect api执行什么样的转换?

android - 更改语言环境后刷新 NavigationView 菜单