在 J2ME 中,我是这样做的:
getClass().getResourceAsStream("/raw_resources.dat");
但是在android中,我总是得到null,为什么?
在 J2ME 中,我是这样做的:
getClass().getResourceAsStream("/raw_resources.dat");
但是在android中,我总是得到null,为什么?
对于原始文件,您应该考虑在 res 目录中创建一个原始文件夹,然后getResources().openRawResource(resourceName)
从您的活动中调用。
InputStream raw = context.getAssets().open("filename.ext");
Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));
在某些情况下,我们必须使用图像名称而不是生成的 id 从可绘制或原始文件夹中获取图像
// 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);
一种先进的方法是使用 Kotlin扩展功能
fun Context.getRawInput(@RawRes resourceId: Int): InputStream {
return resources.openRawResource(resourceId)
}
一件更有趣的事情是在 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:: txtview hello:: res/raw 文件夹中的 .txt 文件(您也可以访问任何其他文件夹)
Ist 2 行是 2 写在 onCreate() 方法中
剩下的要写在扩展Activity的类中!!
getClass().getResourcesAsStream()
在安卓上运行良好。只需确保您尝试打开的文件正确嵌入到您的 APK 中(以 ZIP 格式打开 APK)。
通常在 Android 上,您将此类文件放在assets
目录中。因此,如果您将 放在项目raw_resources.dat
的assets
子目录中,它将最终在assets
APK 中的目录中,您可以使用:
getClass().getResourcesAsStream("/assets/raw_resources.dat");
还可以自定义构建过程,使文件不会出现assets
在 APK 的目录中。
InputStream in = getResources().openRawResource(resourceName);
这将正常工作。在此之前,您必须在原始资源中创建 xml 文件/文本文件。然后就可以访问了。
编辑
如果布局文件或图像名称有任何错误,有时会导入 com.andriod.R。因此,您必须正确导入包,然后才能访问原始文件。
这对我有用:getResources().openRawResource(R.raw.certificate)