我的/ 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(); } }
如果您res/raw/textfile.txt通过“活动/窗口小部件”调用中有文件:
res/raw/textfile.txt
getResources().openRawResource(...) 返回一个 InputStream
getResources().openRawResource(...)
InputStream
点实际上应该是在R.raw中找到的整数…可能与您的文件名相对应R.raw.textfile(通常是不带扩展名的文件的名称)
R.raw.textfile
new BufferedInputStream(getResources().openRawResource(...)); 然后以流的形式读取文件的内容
new BufferedInputStream(getResources().openRawResource(...));