1

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));
    }
}
ono
  • 2,984
  • 9
  • 43
  • 85
  • just found this. it may help http://stackoverflow.com/questions/5771366/reading-a-simple-text-file – ono May 06 '13 at 20:55
  • no, in that example they store file in asset/ not in raw/ – Sruit A.Suk May 06 '13 at 20:57
  • To access raw resources, use `Resources.openRawResource()` with the resource ID, which is `R.raw.filename`. Or you could move the file to the `assets` directory and use the `AssetManager` to get it. These files are in your APK, they aren't in the file system, so you can't simply create a `File` object and open it. – David Wasser May 06 '13 at 20:59

1 Answers1

2

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();
     }
Community
  • 1
  • 1
Sruit A.Suk
  • 7,073
  • 7
  • 61
  • 71