Merge code which extracts assets from APK to file

BUG=609122

Review-Url: https://codereview.chromium.org/2006703004
Cr-Commit-Position: refs/heads/master@{#396620}


CrOS-Libchrome-Original-Commit: 6efc98a62239ae265d3a643a8e5fffa4ee30358a
diff --git a/base/android/java/src/org/chromium/base/FileUtils.java b/base/android/java/src/org/chromium/base/FileUtils.java
index fbaec8c..2c0d8f5 100644
--- a/base/android/java/src/org/chromium/base/FileUtils.java
+++ b/base/android/java/src/org/chromium/base/FileUtils.java
@@ -4,7 +4,14 @@
 
 package org.chromium.base;
 
+import android.content.Context;
+
+import java.io.BufferedOutputStream;
 import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
 
 /**
  * Helper methods for dealing with Files.
@@ -28,4 +35,42 @@
 
         if (!currentFile.delete()) Log.e(TAG, "Failed to delete: " + currentFile);
     }
+
+    /**
+     * Extracts an asset from the app's APK to a file.
+     * @param context
+     * @param assetName Name of the asset to extract.
+     * @param dest File to extract the asset to.
+     * @return true on success.
+     */
+    public static boolean extractAsset(Context context, String assetName, File dest) {
+        InputStream inputStream = null;
+        OutputStream outputStream = null;
+        try {
+            inputStream = context.getAssets().open(assetName);
+            outputStream = new BufferedOutputStream(new FileOutputStream(dest));
+            byte[] buffer = new byte[8192];
+            int c;
+            while ((c = inputStream.read(buffer)) != -1) {
+                outputStream.write(buffer, 0, c);
+            }
+            inputStream.close();
+            outputStream.close();
+            return true;
+        } catch (IOException e) {
+            if (inputStream != null) {
+                try {
+                    inputStream.close();
+                } catch (IOException ex) {
+                }
+            }
+            if (outputStream != null) {
+                try {
+                    outputStream.close();
+                } catch (IOException ex) {
+                }
+            }
+        }
+        return false;
+    }
 }