Java Me-Android如何访问我放入res文件夹的原始资源?
在J2ME中,我这样做是这样的:getClass().getResourceAsStream("/raw_resources.dat");
但是在android中,我总是对此无效,为什么呢?
7个解决方案
123 votes
对于原始文件,您应该考虑在res目录中创建一个原始文件夹,然后从您的活动中调用getResources().openRawResource(resourceName)。
Samuh answered 2020-01-15T06:20:30Z
25 votes
InputStream raw = context.getAssets().open("filename.ext");
Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));
Adrian Vintu answered 2020-01-15T06:20:10Z
14 votes
在某些情况下,如果生成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);
sravan answered 2020-01-15T06:20:50Z
5 votes
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您好:: res / raw文件夹中的.txt文件(您可以通过wel访问ny othr文件夹)
第2行是用onCreate()方法编写的2行
剩下的要写在扩展Activity的课堂上!
poojan9118 answered 2020-01-15T06:21:19Z
5 votes
一种先进的方法是使用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() }
}
yoAlex5 answered 2020-01-15T06:21:48Z
3 votes
InputStream in = getResources()。openRawResource(resourceName);
这将正常工作。 在此之前,您必须在原始资源中创建xml文件/文本文件。 然后它将可以访问。
编辑
如果布局文件或图像名称有任何错误,有时会导入com.android.R。 因此,您必须正确导入软件包,然后才可以访问原始文件。
java dev answered 2020-01-15T06:22:21Z
3 votes
assets在Android上可以正常运行。 只要确保您要打开的文件已正确嵌入APK中即可(以ZIP格式打开APK)。
通常在Android上,您会将此类文件放在assets目录中。 因此,如果将raw_resources.dat放在项目的assets子目录中,它将最终出现在APK的assets目录中,并且可以使用:
getClass().getResourcesAsStream("/assets/raw_resources.dat");
也可以自定义构建过程,以使文件不会进入APK的assets目录中。
0xF answered 2020-01-15T06:22:51Z