简体   繁体   中英

Android Reading a Text File

I am making a project in Android Studio, I have a text file in my project folder, each time I compile, I want my code to read that .txt file. When everythings finished, I want that .txt file to be inside .apk file. I am not trying to read from SD card etc.

But I am getting "File not found Exception" each time I compile. While using eclipse, when you place the .txt file in same directory as your project, code can find .txt file without problems but in Android Studio, it cannot find text file I just created. Where do I have to place my .txt file inside my project folder?
Here is the code:

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

I used to same method to read text file in Java. I don't understand why it isn't working on Android since it uses Java too.

EDIT------

I used asset manager but I got the same error again

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

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

Read Text file From Assets :

Create raw folder in Resources directory:

Paste your file in 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 it will help you.

To complete R. Adang comment : You're looking for the assets folder. You have to place it at the same place as the res folder. File in assets will be included in the APK.

You can access your files in assets by using AssetManager . Get your instance of AssetManager by using context.getAssets()

File access is not only java thing in this case, you have the android here as well and this can make problem. THe thing you're tring to by using File is opening file from application location. To get to you file directory you should use: context.getFilesDir()

than you use basic File constructor. I hope this is what you're looking for

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