Search code examples
javaandroidfileloadbufferedreader

Reading txt files in android... File not found


This is the second thread that I have started for the same question since I did not get a right answer/working answer for my earlier question. I am trying to read a text file from my assests folder. The code works on the desktop but does not on Android. I understand I need a context or an asset manager but then I cannot get resolve method. I have tried everything so far, but I am unable to find a tutorial that works. I even changed the java version to 1.7 to get the try with resources. I am still a noob, so any help would be great. Here is the full class of reading the file and generating a word.

public class WordGenerator {

public String randomWord;
public Random rand;
public char [] randomWordChar;


public ArrayList<String> words = new ArrayList<String>();

private Context mCtx; //<-- declare a Context reference

public void WordGenerator() {


    rand = new Random();

    String all = new String("words.txt");
    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);
    }
        int size = words.size();
        Random rn = new Random();
        int randWord = rn.nextInt(size);
        randomWord = words.get(randWord);
        randomWordChar = randomWord.toCharArray();
    }

}

I even had a couple of tries of separating the load process into a different void class but failed. If possible help thank you. Here is the link to the other question so u know the answers that did not work!!

Reading a plain text file


Solution

  • You should use android.content.Context to get the "getAssets()" method working.

    Observed you are using javax.naming.Context for the context.