Sel*_*ier 33 java resources android file
我在/ 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();
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试了不同的路径语法但总是得到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();
}
}
Run Code Online (Sandbox Code Playgroud)
Ken*_*net 28
如果您res/raw/textfile.txt的Activity/Widget调用中有一个文件:
getResources().openRawResource(...) 返回一个 InputStream
该点实际上应该是在R.raw发现了一个整数...对应的文件名,可能R.raw.textfile(这通常是不带扩展名的文件名)
new BufferedInputStream(getResources().openRawResource(...)); 然后以流的形式读取文件的内容
| 归档时间: |
|
| 查看次数: |
76548 次 |
| 最近记录: |