如何从资产文件获取URI?

我一直在尝试获取资产文件的URIpath。

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

当我检查文件是否存在,我看到该文件不存在

 File f = new File(filepath); if (f.exists() == true) { Log.e(TAG, "Valid :" + filepath); } else { Log.e(TAG, "InValid :" + filepath); } 

有人可以告诉我怎样才能提到资产文件夹中存在的文件的绝对path

没有“资产文件夹中存在文件的绝对path”。 您项目的assets/文件夹的内容打包在APK文件中。 使用AssetManager对象来获取资产上的InputStream

编辑

要修复下面我的评论之一,资产的URL语法是file:///android_asset/... (注意:三个斜杠)。

正确的url是:

 file:///android_asset/RELATIVEPATH 

RELATIVEPATH是资源相对于资产文件夹的path。

注意scheme中的3个。 Web视图不会加载我的任何资产没有3.我试过2(以前)评论CommonsWare,它不会工作。 然后我看了CommonsWare在github上的源代码,注意到了额外的正斜杠。

这个testing虽然只在1.6 Android模拟器上完成,但是我怀疑它在真实设备或更高版本上的不同。

编辑:CommonsWare更新了他的答案,以反映这个微小的变化。 所以我编辑了这个,所以现在的答案还是有意义的。

适用于WebView,但似乎在URL.openStream()上失败。 因此,您需要区分file://协议,并按照build议通过AssetManager处理它们。

在这里输入图像描述

请确保您的资产文件夹放置正确。

试试这个:它的工作

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

如果你有空值exception请试试这个:

 InputStream in_s1 = TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml"); 

TopBranData是一个类

 InputStream is = getResources().getAssets().open("terms.txt"); String textfile = convertStreamToString(is); public static String convertStreamToString(InputStream is) throws IOException { Writer writer = new StringWriter(); char[] buffer = new char[2048]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } String text = writer.toString(); return text; 

请尝试此代码工作正常

  Uri imageUri = Uri.fromFile(new File("//android_asset/luc.jpeg")); /* 2) Create a new Intent */ Intent imageEditorIntent = new AdobeImageIntent.Builder(this) .setData(imageUri) .build(); 

是的,你不能从你的Android手机或模拟器访问你的驱动器文件夹,因为你的电脑和Android是两个不同的OS.I将去Android的res文件夹,因为它有很好的资源pipe理方法。 直到除非你有很好的理由把你的文件放在assets文件夹中。 相反,你可以做到这一点

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

尝试这个 :

 Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.cat); 

我做了它,它的工作

为我工作试试这个代码

  uri = Uri.fromFile(new File("//assets/testdemo.txt")); File f = new File(testfilepath); if (f.exists() == true) { Toast.makeText(getApplicationContext(),"valid :" + testfilepath, 2000).show(); } else { Toast.makeText(getApplicationContext(),"invalid :" + testfilepath, 2000).show(); }