Reading a plain text file

本秂侑毒 提交于 2019-12-11 04:54:23

问题


I know this topic probably has been covered before but I cant find an answer to the my problem.
I have a file that contains some words I need to read.
It works normally on my desktop version, but wen I try to run on an emulator, I get java.io.FileNotFoundException - no file found.
I understand I have to load the file in a different way than the desktop.

Any help would be appreciated.

Here is the code for reading the file.

    String line;

        try {

            BufferedReader br = new BufferedReader(new FileReader("words.txt"));
            if (!br.ready()) {
                throw new IOException();
            }
            while ((line = br.readLine()) != null) {
                words.add(line);
            }
            br.close();
        } catch (IOException e) {
            System.out.println(e);
        }

but that doesn't work on Android!!

STILL NO SOLUTION!!


回答1:


You can reach a file from context in android.

Context Context;
AssetManager mngr = context.getAssets();
String line;
        try {

            BufferedReader br = new BufferedReader(new FileReader(mngr.open("words.txt")));
            if (!br.ready()) {
                throw new IOException();
            }
            while ((line = br.readLine()) != null) {
                words.add(line);
            }
            br.close();
        } catch (IOException e) {
            System.out.println(e);
        }

Or try this:

String line;
        try {

            BufferedReader br = new BufferedReader(new FileReader(getApplicationContext().getAssets().open("words.txt")));
            if (!br.ready()) {
                throw new IOException();
            }
            while ((line = br.readLine()) != null) {
                words.add(line);
            }
            br.close();
        } catch (IOException e) {
            System.out.println(e);
        }



回答2:


Assets are files on your development machine. They are not files on the device.

To get an InputStream on an asset, use open() on an AssetManager. You can get an AssetManager by calling getAssets() on your Activity, Service, or other Context.



来源:https://stackoverflow.com/questions/37228980/reading-a-plain-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!