Ark*_*aha 52 resources android inputstream java-me android-resources
在J2ME中,我这样做:
getClass().getResourceAsStream("/raw_resources.dat");
但是在android中,我总是在这上面为空,为什么?
小智 25
InputStream raw = context.getAssets().open("filename.ext");
Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));
Run Code Online (Sandbox Code Playgroud)
小智 14
在某些情况下,如果生成了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);
Run Code Online (Sandbox Code Playgroud)
一种先进的方法是使用Kotlin 扩展功能
fun Context.getRawInput(@RawRes resourceId: Int): InputStream {
return resources.openRawResource(resourceId)
}
Run Code Online (Sandbox Code Playgroud)
另一有趣的事情是在Closeable范围内定义的扩展功能使用
例如,您可以以优雅的方式使用输入流,而无需处理异常和内存管理
fun Context.readRaw(@RawRes resourceId: Int): String {
return resources.openRawResource(resourceId).bufferedReader(Charsets.UTF_8).use { it.readText() }
}
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
在res / raw文件夹中的TextView01 :: txtview在hello ::。txt文件中(您可以通过wel访问ny othr文件夹)
第2行是用onCreate()方法编写的2行
剩下的要写在扩展Activity的课堂上!
getClass().getResourcesAsStream()在 Android 上运行良好。只需确保您尝试打开的文件正确嵌入到您的 APK 中(以 ZIP 格式打开 APK)。
通常在 Android 上,您将此类文件放在assets目录中。因此,如果您将 放在项目raw_resources.dat的assets子目录中,它将最终assets位于 APK中的目录中,您可以使用:
getClass().getResourcesAsStream("/assets/raw_resources.dat");
Run Code Online (Sandbox Code Playgroud)
还可以自定义构建过程,使文件不会assets出现在 APK的目录中。
| 归档时间: |
|
| 查看次数: |
112474 次 |
| 最近记录: |