Ber*_*rnd 76 file-io resources android
我想从res/raw /文件夹中打开一个文件.我绝对相信文件存在.要打开我试过的文件
File ddd = new File("res/raw/example.png");
Run Code Online (Sandbox Code Playgroud)
命令
ddd.exists();
Run Code Online (Sandbox Code Playgroud)
收益率为假.所以这种方法不起作用.
试
MyContext.getAssets().open("example.png");
Run Code Online (Sandbox Code Playgroud)
以getMessage()"null"结束异常.
简单地使用
R.raw.example
Run Code Online (Sandbox Code Playgroud)
因为文件名仅在运行时作为字符串被识别,所以是不可能的.
为什么访问文件夹/ res/raw /中的文件如此困难?
Ber*_*rnd 133
在给定链接的帮助下,我能够自己解决问题.正确的方法是获取资源ID
getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
"raw", getPackageName());
Run Code Online (Sandbox Code Playgroud)
将其作为InputStream
InputStream ins = getResources().openRawResource(
getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
"raw", getPackageName()));
Run Code Online (Sandbox Code Playgroud)
Emi*_*Adz 39
以下是从raw文件夹中获取XML文件的示例:
InputStream XmlFileInputStream = getResources().openRawResource(R.raw.taskslists5items); // getting XML
Run Code Online (Sandbox Code Playgroud)
然后你可以:
String sxml = readTextFile(XmlFileInputStream);
Run Code Online (Sandbox Code Playgroud)
什么时候:
public String readTextFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
Run Code Online (Sandbox Code Playgroud)
小智 13
您可以使用原始/ res读取文件getResources().openRawResource(R.raw.myfilename).
但是有一个IDE限制,您使用的文件名只能包含小写字母数字字符和点.所以文件名喜欢XYZ.txt或my_data.bin不会在R中列出.
您可以通过以下两种方法使用 Kotlin 读取原始资源。
可以通过获取资源id来获取。或者,您可以使用字符串标识符,您可以在其中以编程方式增量更改文件名。
队友的欢呼声
// R.raw.data_post
this.context.resources.openRawResource(R.raw.data_post)
this.context.resources.getIdentifier("data_post", "raw", this.context.packageName)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
126165 次 |
| 最近记录: |