访问安卓系统中的资源文件
我的/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();
}
}
我尝试了不同的路径语法,但总是得到一个java.io.FileNotFoundException错误。如何访问 /res/raw/textfile.txt 进行处理?File file = new File(“res/raw/textfile.txt”); Android 中的方法有误吗?
答案: *****
// 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();
}
}
请注意,这将不返回任何内容,但会将内容作为字符串逐行打印到日志中。DEBUG