How to reference a File in raw folder in Android

后端 未结 4 1207
陌清茗
陌清茗 2020-12-03 08:37

I just want to create a File object like this

File myImageFile = new File (\"image1\") ;

but it is giving me exception of FileNotFou

4条回答
  •  再見小時候
    2020-12-03 08:55

    Generally you access the files through getResources().openRawResource(R.id._your_id). If you absolutely need a File reference to it, one option is to copy it over to internal storage:

    File file = new File(this.getFilesDir() + File.separator + "DefaultProperties.xml");
    try {
            InputStream inputStream = resources.openRawResource(R.id._your_id);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
    
            byte buf[]=new byte[1024];
            int len;
            while((len=inputStream.read(buf))>0) {
                fileOutputStream.write(buf,0,len);
            }
    
            fileOutputStream.close();
            inputStream.close();
        } catch (IOException e1) {}
    

    Now you have a File that you can access anywhere you need it.

提交回复
热议问题