Uni835
Uni835

Reputation: 27

FileUtils.readFileToString IOException

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" />

Upvotes: 1

Views: 1567

Answers (2)

Ye Myat Thu
Ye Myat Thu

Reputation: 187

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());

Upvotes: 1

rookiedev
rookiedev

Reputation: 1127

According to the Commons IO 2.4 API, the readFileToString method will take a file as parameter then read the contents of a file into a String. However,the getExternalStoragePublicDirectory method returns a folder instead of a file so calling readFileToString will throw an IO exception.

Upvotes: 0

Related Questions