ono
ono

Reputation: 3102

Reading .txt file to list Android / FileNotFound

I'm attempting to read a .txt file and appending it to an ArrayList. It seems to fail at the Scanner line with 'java.io.FileNotFoundException: /raw/words.txt: open failed: (No such file or directory)'. I've tried BufferReader method and changing the location of the file with little success. Why is it not recognizing the file?

public void openFile (){
    File file = new File("raw/words.txt");
    ArrayList<String> names = new ArrayList<String>();
    try{
    Scanner in = new Scanner (file);
    while (in.hasNextLine()){
        names.add(in.nextLine());
    }
    }
    catch (Exception e){
    e.printStackTrace();
    }
    Collections.sort(names);
    for(int i=0; i<names.size(); ++i){
        System.out.println(names.get(i));
    }
}

Upvotes: 1

Views: 293

Answers (1)

Sruit A.Suk
Sruit A.Suk

Reputation: 7263

Yes, you can't specific by just raw/words.txt like that, the android doesn't store path as same as desktop pc

you need to get their resources and read it

for example copy from here

// to call this method
// String answer = readRawTextFile(mContext, R.raw.words);

public static String readRawTextFile(Context ctx, int resId)
     {
          InputStream inputStream = ctx.getResources().openRawResource(resId);

             InputStreamReader inputreader = new InputStreamReader(inputStream);
             BufferedReader buffreader = new BufferedReader(inputreader);
              String line;
              StringBuilder text = new StringBuilder();

              try {
                while (( line = buffreader.readLine()) != null) {
                    text.append(line);
                    text.append('\n');
                  }
            } catch (IOException e) {
                return null;
            }
              return text.toString();
     }

Upvotes: 2

Related Questions