Home > front end >  How to choose a txt file from raw folder, get path and read data?
How to choose a txt file from raw folder, get path and read data?

Time:04-17

I have a big text file of about 40mbs, I have been looking for a way to read its contents and I found this:

File f = new File(String.valueOf(getResources().openRawResource(R.raw.test)));

try {
    FileInputStream inputStream = new FileInputStream(f);
    Scanner sc = new Scanner(inputStream, "UTF-8");
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

Unfortunately I am getting the following error:

java.io.FileNotFoundException: android.content.res.AssetManager$AssetInputStream@ead83c (No such file or directory)

The file I am trying to access is in raw folder, and its name is test.txt

Where am I getting it wrong?

CodePudding user response:

Resources.openRawResource already gives you an InputStream.

final InputStream inputStream = getResources().openRawResource(R.raw.test);
try {
    Scanner sc = new Scanner(inputStream, "UTF-8");
    // ...
} finally {
    in.close();
}

Raw resources are packed inside the APK. They're not accessible using a file system path you're used to.

  • Related