How to get URI from an asset File?

后端 未结 11 1488
慢半拍i
慢半拍i 2020-11-22 14:27

I have been trying to get the URI path for an asset file.

uri = Uri.fromFile(new File(\"//assets/mydemo.txt\"));

When I check if the file

相关标签:
11条回答
  • 2020-11-22 14:52

    Try this out, it works:

    InputStream in_s = 
        getClass().getClassLoader().getResourceAsStream("TopBrands.xml");
    

    If you get a Null Value Exception, try this (with class TopBrandData):

    InputStream in_s1 =
        TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");
    
    0 讨论(0)
  • 2020-11-22 14:53

    Yeah you can't access your drive folder from you android phone or emulator because your computer and android are two different OS.I would go for res folder of android because it has good resources management methods. Until and unless you have very good reason to put you file in assets folder. Instead You can do this

    try {
          Resources res = getResources();
          InputStream in_s = res.openRawResource(R.raw.yourfile);
    
          byte[] b = new byte[in_s.available()];
          in_s.read(b);
          String str = new String(b);
        } catch (Exception e) {
          Log.e(LOG_TAG, "File Reading Error", e);
     }
    
    0 讨论(0)
  • 2020-11-22 14:56

    Finally, I found a way to get the path of a file which is present in assets from this answer in Kotlin. Here we are copying the assets file to cache and getting the file path from that cache file.

    @Throws(IOException::class)
        fun getFileFromAssets(context: Context, fileName: String): File = File(context.cacheDir, fileName)
                .also {
                   if (!it.exists()) {
                    it.outputStream().use { cache ->
                        context.assets.open(fileName).use { inputStream ->
                                inputStream.copyTo(cache)
                        }
                      }
                    }
                }
    

    Get the path to the file like:

    val filePath =  getFileFromAssets(context, "fileName.extension").absolutePath
    
    0 讨论(0)
  • 2020-11-22 14:59

    Worked for me Try this code

       uri = Uri.fromFile(new File("//assets/testdemo.txt"));
       String testfilepath = uri.getPath();
        File f = new File(testfilepath);
        if (f.exists() == true) {
        Toast.makeText(getApplicationContext(),"valid :" + testfilepath, 2000).show();
        } else {
       Toast.makeText(getApplicationContext(),"invalid :" + testfilepath, 2000).show();
     }
    
    0 讨论(0)
  • 2020-11-22 15:08

    Please try this code working fine

     Uri imageUri = Uri.fromFile(new File("//android_asset/luc.jpeg"));
    
        /* 2) Create a new Intent */
        Intent imageEditorIntent = new AdobeImageIntent.Builder(this)
                .setData(imageUri)
                .build();
    
    0 讨论(0)
提交回复
热议问题