Reputation: 525
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" ?
Upvotes: 5
Views: 1992
Reputation: 52810
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.
Upvotes: 3
Reputation: 4641
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
Upvotes: -1
Reputation: 424
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()
Upvotes: 0