• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 package org.chromium.base;
6 
7 import android.content.Context;
8 
9 import java.io.BufferedOutputStream;
10 import java.io.File;
11 import java.io.FileOutputStream;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.io.OutputStream;
15 
16 /**
17  * Helper methods for dealing with Files.
18  */
19 public class FileUtils {
20     private static final String TAG = "FileUtils";
21 
22     /**
23      * Delete the given File and (if it's a directory) everything within it.
24      */
recursivelyDeleteFile(File currentFile)25     public static void recursivelyDeleteFile(File currentFile) {
26         assert !ThreadUtils.runningOnUiThread();
27         if (currentFile.isDirectory()) {
28             File[] files = currentFile.listFiles();
29             if (files != null) {
30                 for (File file : files) {
31                     recursivelyDeleteFile(file);
32                 }
33             }
34         }
35 
36         if (!currentFile.delete()) Log.e(TAG, "Failed to delete: " + currentFile);
37     }
38 
39     /**
40      * Extracts an asset from the app's APK to a file.
41      * @param context
42      * @param assetName Name of the asset to extract.
43      * @param dest File to extract the asset to.
44      * @return true on success.
45      */
extractAsset(Context context, String assetName, File dest)46     public static boolean extractAsset(Context context, String assetName, File dest) {
47         InputStream inputStream = null;
48         OutputStream outputStream = null;
49         try {
50             inputStream = context.getAssets().open(assetName);
51             outputStream = new BufferedOutputStream(new FileOutputStream(dest));
52             byte[] buffer = new byte[8192];
53             int c;
54             while ((c = inputStream.read(buffer)) != -1) {
55                 outputStream.write(buffer, 0, c);
56             }
57             inputStream.close();
58             outputStream.close();
59             return true;
60         } catch (IOException e) {
61             if (inputStream != null) {
62                 try {
63                     inputStream.close();
64                 } catch (IOException ex) {
65                 }
66             }
67             if (outputStream != null) {
68                 try {
69                     outputStream.close();
70                 } catch (IOException ex) {
71                 }
72             }
73         }
74         return false;
75     }
76 }
77