Reading Android Studio from Raw Resource Text File

I am trying to save a .txt file in a res \ raw file in Android Studio and read / analyze the file. I have the file "my_file.txt" in the "raw" folder that I created in the "res" directory (which I did not create).

Here's what I think my main problem is: when creating a File object (for use with a Scanner object), what path should I go for my text file?

Here is my code:

private void readFile(){ Scanner scanner = null; try { scanner = new Scanner(new File("\\res\\raw\\my_file.txt")); //I've also tried without the .txt extension Log.v("readFile->try","Trying to read file."); }catch(Exception e) { //Send error message. } if(scanner != null) { while (scanner.hasNext()) { String[] line = scanner.nextLine().split("\t"); //Process string here } } } 
+2
source share
2 answers

Think you're looking for something in the lines

 InputStream is = ctx.getResources().openRawResource(res_id); 

Where ctx is an instance of context

+5
source

I suggest you put it in the assets folder in the src/main folder. Then you can use the getAssets method to extract a file like this

  InputStream in = (Activity)getContext().getAssets().open("my_file.txt") 

If the folder does not exist, create it: - /

+2
source

All Articles