Android: how do I create File object from asset file?

后端 未结 3 554
时光说笑
时光说笑 2020-12-03 07:28

I have a text file in the assets folder that I need to turn into a File object (not into InputStream). When I tried this, I got \"no such file\" exception:

S         


        
相关标签:
3条回答
  • 2020-12-03 07:38

    You cannot get a File object directly from an asset, because the asset is not stored as a file. You will need to copy the asset to a file, then get a File object on your copy.

    0 讨论(0)
  • 2020-12-03 07:43

    You cannot get a File object directly from an asset.

    First, get an inputStream from your asset using for example AssetManager#open

    Then copy the 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();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-03 07:54

    This function missing in code. @wadali

    private void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while((read = in.read(buffer)) != -1){
          out.write(buffer, 0, read);
        }
    }
    

    Source: https://stackoverflow.com/a/4530294/4933464

    0 讨论(0)
提交回复
热议问题