Programmatically populate file field using Entity API
Ok, I found the answer to this question here.

Instead of:

        $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
        $entity-&gt;$key= (array)$file;


It should be:

        $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
        if($file !== false)
        {              
          $entity-&gt;$key-&gt;file-&gt;set($file);
        }


This 'if($file !== false)' is optional just to be sure that we're passing a file object.


  *Note that the difference is that we're not passing the file object as an array and also we're passing it to a 'file' atribute instead of
  passing it directly to the field.