Reading a plain text file

2019-08-14 18:06发布

问题:

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.