Android Reading Text File

I am doing a project in Android Studio, I have a text file in my project folder, every time I compile I want my code to read this .txt file. When it's over, I want this .txt file to be inside the .apk file. I am not trying to read from SD card etc.

But I get "File not found Exception" every time I compile. When using eclipse, when you put the .txt file in the same directory as your project, the code can find the .txt file without issue, but in Android Studio, it cannot find the text file I just created. Where should I put my .txt file in my project folder?
Here is the code:

FileReader in = new FileReader("TEXTgreetingKeywords.txt"); 
final BufferedReader br = new BufferedReader(new InputStreamReader(in));

      

I used the same method to read a text file in Java. I don't understand why it doesn't work on Android as it uses Java as well.

EDIT ------

I used asset manager but got the same error again

AssetManager asset = getAssets();
    try {
         in = asset.open("text.txt");
    } catch (IOException e) {
        e.printStackTrace();
    }

      

Should I change the directory to something like "C: \ App \ main \ text.txt"?

+3


source to share


3 answers


To end R. Adang's comment: You are looking for a folder assets

. You must place it in the same location as the folder res

. The file assets

will be included in the APK.



You can access your files assets

using the AssetManager . Get your AssetManager instance withcontext.getAssets()

+1


source


Read the text . From Assets :

Create source folder in resource directory:

Paste your file into the raw folder :



Read text from file :

private String readText() {
        InputStream inputStream = getResources().openRawResource(
                R.raw.license_agreement);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int i;
        try {
            i = inputStream.read();
            while (i != -1) {
                byteArrayOutputStream.write(i);
                i = inputStream.read();
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream.toString();
    }

      

Hope this helps you.

+1


source


File access is not just a java thing in this case, you have android here and that might make the problem. What you are trying to use with File

is opening the file from the app location. To get a directory of files, you have to use:context.getFilesDir()

than you are using the base constructor File

. Hope this is what you are looking for.

0


source







All Articles