在J2ME中,我会像这样做:
getClass().getResourceAsStream("/raw_resources.dat");
但在安卓中,我总是得到null,为什么?getClass().getResourceAsStream("/raw_resources.dat");
但在安卓中,我总是得到null,为什么?对于原始文件,您应该考虑在res目录下创建一个raw文件夹,然后从您的活动中调用getResources().openRawResource(resourceName)
。
InputStream raw = context.getAssets().open("filename.ext");
Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));
assets
文件夹很有用。 - Caner在某些情况下,我们需要根据图像名称而不是生成的ID从drawable或raw文件夹中获取图像。
// Image View Object
mIv = (ImageView) findViewById(R.id.xidIma);
// create context Object for to Fetch image from resourse
Context mContext=getApplicationContext();
// getResources().getIdentifier("image_name","res_folder_name", package_name);
// find out below example
int i = mContext.getResources().getIdentifier("ic_launcher","raw", mContext.getPackageName());
// now we will get contsant id for that image
mIv.setBackgroundResource(i);
Android访问原始资源
一种先进的方式是使用Kotlin 扩展函数
fun Context.getRawInput(@RawRes resourceId: Int): InputStream {
return resources.openRawResource(resourceId)
}
还有一个有趣的东西是扩展函数use,它在Closeable作用域中定义。
例如,您可以优雅地处理输入流,而无需处理异常和内存管理。
fun Context.readRaw(@RawRes resourceId: Int): String {
return resources.openRawResource(resourceId).bufferedReader(Charsets.UTF_8).use { it.readText() }
}
TextView txtvw = (TextView)findViewById(R.id.TextView01);
txtvw.setText(readTxt());
private String readTxt()
{
InputStream raw = getResources().openRawResource(R.raw.hello);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try
{
i = raw.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = raw.read();
}
raw.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
TextView01:: 线性布局中的文本视图
hello:: res/raw文件夹中的.txt文件(您也可以访问其他文件夹)
前两行代码应写在onCreate()方法中
其余代码应写在扩展Activity类中!
getClass().getResourcesAsStream()
在安卓上可以正常使用。只需确保您要打开的文件已正确嵌入您的 APK 中(将 APK 作为 ZIP 文件打开即可)。
通常在安卓上,您会将这些文件放在 assets
目录中。因此,如果您将 raw_resources.dat
放在项目的 assets
子目录中,它将出现在 APK 的 assets
目录中,您可以使用以下代码:
getClass().getResourcesAsStream("/assets/raw_resources.dat");
你还可以定制构建过程,使文件不落入APK的assets
目录中。
assets
文件夹位于src/main/assets
。 - ErhannisInputStream in = getResources().openRawResource(resourceName);
这段代码是正确的。在此之前,您需要在原始资源中创建XML文件/文本文件才能访问它。
编辑:
有时,如果布局文件或图像名称存在错误,则会导入com.andriod.R。因此,您必须正确导入包才能访问原始文件。
getResources().openRawResource(R.raw.certificate)