zoukankan      html  css  js  c++  java
  • 关于Android Assets读取文件为File对象

    关于Android Assets读取文件为File对象的问题,在Assets里面放置文件,在使用的时候,一般是使用AssetManger对象,open方法获取InputStream

    然后进行其他操作.

    这里遇到了这样需求,直接把Assets里面文件读取为一个File对象,找了半天,没有找到这样方法,搜索了很久,发现这样是行不通的.

    是不能直接从asset获取然后直接转换为File对象的,因为asset被存储为apk中,除非你解压Apk文件,一般是不能找到一个Path实例化一个File对象的,

    这里也有特殊情况,webview可以根据asset的路径加载在asset存放的.html文件:

    WebView wv = new WebView(context);      
    wv.loadUrl("file:///android_asset/help/index.html");

    如果需要一个File的时候,需要从新拷贝一份,把File存储在设备上,

    然后再使用。

    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();
            }
        }
    }
    

    或者直接InputStream转换为String,然后执行其他操作.

       AssetManager am = getActivity().getAssets();
                InputStream inputStream = am.open("chapter1/ObservableVSIterator.java");
                String json = null;
                try {
                    int size = inputStream.available();
                    byte[] buffer = new byte[size];
                    inputStream.read(buffer);
                    inputStream.close();
                    json = new String(buffer, "UTF-8");
                } catch (IOException ex) {
                    ex.printStackTrace();
                    return null;
         }
    
  • 相关阅读:
    -1.#IND000 &&图像类型转换
    三维点集拟合:平面拟合、RANSAC、ICP算法
    深度学习:又一次推动AI梦想(Marr理论、语义鸿沟、视觉神经网络、神经形态学)
    三维重建:Kinect几何映射-SDK景深数据处理
    《SLIC Superpixels》阅读笔记
    中国企业系列
    关于抠图的一些文章方法收集
    数学空间引论
    PCL:解决PCL和OpenCV冲突的方法
    游戏开发:OpenGL入门学习
  • 原文地址:https://www.cnblogs.com/spring87/p/5990156.html
Copyright © 2011-2022 走看看