开发者

FileReader for text file in Android

Good times!

My Android app 开发者_开发知识库is trying to read simple text file, using usual Java combination

FileReader fr = new FileReader("file:///android_asset/example.txt");
BufferedReader bfr = new BufferedReader(fr);

But what ever I do, I'm getting File not Found exeption, although there is another html-file in this directory and shown in WebView correctly.

So, my question is:

FileReader can be used for simple reading text file or I have to use InputStream ?


You have to InputStream like as follows.Change the code like this.I hope it will work:

FileInputStream fis = new FileInputStream("file:///android_asset/example.txt");
BufferedReader bfr = new BufferedReader(new InputStreamReader(fis));


Use getAssets() method.

BufferedReader br=new BufferedReader(new 
            InputStreamReader(getAssets().open("example.txt")));


Android doesn't know where your files are located. You have to use their functions. See the section called data storage, especially the section on internal storage and the methods in the Android Context class for opening and writing to files. For example you could use the Context method getFileStreamPath to get a Java File object and pass that to a Java FileReader.

File yourFile = getFileStreamPath(YOUR_FILENAME);
if (yourFile.exists()) {
    BufferedReader in = new BufferedReader(new FileReader(yourFile));
    ...
    in.close();
}

P.S. Here's a very similar question and answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜