简体   繁体   中英

Read file from Android Assets with FileReader

I'm trying to read a files from assets but it is neither reading the file nor throwing the exception. I'm working on an OCR system, that reads the word or sentence and extract the names from it by comparing the words or group of alphabets with the ArrayList made from that "names.txt" file. Names are about 15000, each name is stored in seperate/single line. Actually, I'm adding these names to the ArrayList to find out if particular name exists in that file. Everything is done and tested, the only thing that is left is reading the file. I've tried the same code with java IDE that reads the files from drive and it's working on Java ide but not in Android Studio. Tried piece of code:

FileReader freader = new FileReader("file:///android_asset/names.txt");
BufferedReader br = new BufferedReader(freader);

I've also tried,

FileReader freader = new FileReader(getAssets().open("names.txt"));
BufferedReader br = new BufferedReader(freader);

gives the error

Error:(1387, 26) error: no suitable constructor found for FileReader(InputStream)
constructor FileReader.FileReader(File) is not applicable (argument mismatch; InputStream cannot be converted to File)
constructor FileReader.FileReader(FileDescriptor) is not applicable (argument mismatch; InputStream cannot be converted to FileDescriptor)
constructor FileReader.FileReader(String) is not applicable (argument mismatch; InputStream cannot be converted to String)"

And also this:

FileReader freader = new FileReader(context.getAssets().open("names.txt"));
BufferedReader br = new BufferedReader(freader);

That says "cannot resolve symbol 'context' "

The path of the file is here .

You don't need a FileReader . Use a BufferedReader wrapped around an InputStreamReader wrapped around the InputStream you already got from getAssets().open() .

FileReader needs a file system path.

There is no constructor for an input stream.

So no you cannot use FileReader to 'read' files from assets.

Copy the file from assets to the file system.

After that use that file on file system.

If you dont insist in using FileReader you could change

FileReader freader = new FileReader(getAssets().open("names.txt"));
BufferedReader br = new BufferedReader(freader);

to

InputStream is = getAssets().open("images/names.txt");
BufferedReader br = new BufferedReader(is);

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