简体   繁体   中英

Reading from a raw resource text file

I'm trying to keep a .txt file in my res\\raw file in Android Studio and read/parse the file. I have a file "my_file.txt" in a folder called "raw" that I created in the "res" directory (that I didn't create).

Here's what I think my main issue is: When creating the File object (to use with the Scanner object), what path should I pass in for my text file?

Here's 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
        }
    }
}

Think you are looking for something along the lines of

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

Where ctx is a instance of Context

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

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

If the folder does not exists, create one :-/

or You can use this Function

private String readFile()
{
String myData = "";
File myExternalFile = new File("assets/","log.txt");
try {
    FileInputStream fis = new FileInputStream(myExternalFile);
    DataInputStream in = new DataInputStream(fis);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));

    String strLine;
    while ((strLine = br.readLine()) != null) {
        myData = myData + strLine + "\n";
    }
    br.close();
    in.close();
    fis.close();
 } catch (IOException e) 
    {
         e.printStackTrace();
    }
   return myData;
}

just past in the path Location.

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