Android:如何从资产文件创建File对象?

I Z*_*I Z 20 android assets file

我在assets文件夹中有一个文本文件,我需要将其转换为File对象(而不是InputStream).当我尝试这个时,我得到"没有这样的文件"例外:

String path = "file:///android_asset/datafile.txt";
URL url = new URL(path);
File file = new File(url.toURI());  // Get exception here
Run Code Online (Sandbox Code Playgroud)

我可以修改它以使其工作吗?

顺便说一下,我尝试"按示例编写代码",查看我项目中其他位置引用资源文件夹中的HTML文件的代码片段

public static Dialog doDialog(final Context context) {
WebView wv = new WebView(context);      
wv.loadUrl("file:///android_asset/help/index.html");
Run Code Online (Sandbox Code Playgroud)

我承认我并不完全理解上述机制,因此我可能无法正常工作.

谢谢!

Com*_*are 26

您无法File直接从资产获取对象,因为资产不会存储为文件.您需要将资产复制到文件中,然后File在副本上获取对象.

  • 是的,那你怎么做的? (11认同)

Lau*_*t B 10

您无法直接从资产获取File对象.

首先,使用例如AssetManager #open从资产中获取inputStream

然后复制inputStream:

    public static void writeBytesToFile(InputStream is, File file) throws IOException{
    FileOutputStream fos = null;
    try {   
        byte[] data = new byte[2048];
        int nbread = 0;
        fos = new FileOutputStream(file);
        while((nbread=is.read(data))>-1){
            fos.write(data,0,nbread);               
        }
    }
    catch (Exception ex) {
        logger.error("Exception",ex);
    }
    finally{
        if (fos!=null){
            fos.close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)