Java 在 Android 中访问资源文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4081763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access resource files in Android
提问by Selzier
I have a resource file in my /res/raw/ folder (/res/raw/textfile.txt) which I am trying to read from my android app for processing.
我的 /res/raw/ 文件夹(/res/raw/textfile.txt)中有一个资源文件,我试图从我的 android 应用程序中读取以进行处理。
public static void main(String[] args) {
File file = new File("res/raw/textfile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
// Do something with file
Log.d("GAME", dis.readLine());
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I have tried different path syntax but always get a java.io.FileNotFoundExceptionerror. How can I access /res/raw/textfile.txt for processing? Is File file = new File("res/raw/textfile.txt");the wrong method in Android?
我尝试了不同的路径语法,但总是得到java.io.FileNotFoundException错误。如何访问 /res/raw/textfile.txt 进行处理?Is File file = new File("res/raw/textfile.txt"); Android 中的错误方法?
* Answer: *
* 答案:*
// Call the LoadText method and pass it the resourceId
LoadText(R.raw.textfile);
public void LoadText(int resourceId) {
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
采纳答案by Kennet
If you have a file in res/raw/textfile.txt
from your Activity/Widget call:
如果您res/raw/textfile.txt
的 Activity/Widget 调用中有一个文件:
getResources().openRawResource(...)
returns an InputStream
getResources().openRawResource(...)
返回一个 InputStream
The dots should actually be an integer found in R.raw... corresponding to your filename, possibly R.raw.textfile
(it's usually the name of the file without extension)
点实际上应该是在 R.raw 中找到的整数...对应于您的文件名,可能R.raw.textfile
(它通常是没有扩展名的文件名)
new BufferedInputStream(getResources().openRawResource(...));
then read the content of the file as a stream
new BufferedInputStream(getResources().openRawResource(...));
然后以流的形式读取文件的内容