简体   繁体   中英

Reading a plain text file

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!!

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 .

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);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM