I'm new to Android app development. Currently, I'm trying to get Android download folder path and log it. To do this, I use commons io library. I've got this code:
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.e("files", folder.listFiles().length + " items");
try {
String DFOLDER = FileUtils.readFileToString(folder);
Log.i(TAG2, DFOLDER);
}catch (IOException e){
Toast.makeText(getApplicationContext(), R.string.fail,
Toast.LENGTH_SHORT).show();
}
For some reason I'm getting IOException every time, but I'm receiving the amount of files in folder from 2nd line.
I've got this permissions in manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
FileUtils.readFileToString Reads the contents of a file into a String. Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) return a directory, not a file, so using readFileToString on it will throw an IOException. If you want to read the contents of all the files in the Download directory, do something like that.
File folder = Environment.getExternalStoragePublicDirectory(Environmeng t.DIRECTORY_DOWNLOADS);
for(File file:folder.listFiles()){
try {
String DFOLDER = FileUtils.readFileToString(file);
Log.i("File Contents ", DFOLDER);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
If there are too many files in that directory, it will probably throw an OutOfMemoryError.
EDIT: if you need the path of the foler use
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.i("Folder Path",folder.getAbsolutePath());