【问题标题】:Writing to android assets directory at runtime?在运行时写入android资产目录?
【发布时间】:2019-02-02 12:29:24
【问题描述】:

我从网络请求中获取 html sn-ps 更新,需要将它们插入到本地 html 文件中,然后可以在运行时使用 webView.loadUrl 获取该文件。

我可以使用webView.loadUrl 轻松地从/android_assets/myFile.html 加载文件,但我无法写入文件,因为在运行时无法访问/android_assets 目录:Writing to /android_assets at runtime

所以我的问题是,是否有其他位置可以放置 myFile.html,以便我可以在运行时写入它并将其加载到 webView 中?

【问题讨论】:

    标签: android android-webview android-assets


    【解决方案1】:

    为此,您应该从 html 加载内容,对其进行修改,然后将其保存到存储中。

    Usage: String yourData = LoadData("myFile.html");
    
    public String LoadData(String inFile) {
            String tContents = "";
    
        try {
            InputStream stream = getAssets().open(inFile);
    
            int size = stream.available();
            byte[] buffer = new byte[size];
            stream.read(buffer);
            stream.close();
            tContents = new String(buffer);
        } catch (IOException e) {
            // Handle exceptions here
        }
    
        return tContents;    
     }
    

    在 WebView 中加载数据。调用WebView的loadData()方法

    webView.loadData(yourData, "text/html; charset=utf-8", "UTF-8");
    

    【讨论】:

    • 这并不能准确回答问题,因为getAssets() 方法仍然可以到达/android_assets 目录。我正在寻找更改的 HTML 文件的其他位置。不过,你的回答还是很有帮助的!
    【解决方案2】:

    资产目录是只读的,不能动态更改。
    您可以在流动目录中读取&白文件:

    Context.getFilesDir()  
    

    无需许可
    典型位置:/data/data/app.package.name/files/

    Context.getExternalFilesDir(null)  
    

    当 api 级别 典型位置:/sdcard/Android/data/app.package.name/files/

    Environment.getExternalStorageDirectory()  
    

    需要 WRITE_EXTERNAL_STORAGE
    典型位置:/sdcard/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-16
      • 1970-01-01
      • 2013-01-13
      • 2013-01-10
      • 1970-01-01
      • 2014-09-20
      相关资源
      最近更新 更多