Home | History | Annotate | Download | only in android_scripting
      1 /*
      2  * Copyright (C) 2016 Google Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
      5  * use this file except in compliance with the License. You may obtain a copy of
      6  * the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
     12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
     13  * License for the specific language governing permissions and limitations under
     14  * the License.
     15  */
     16 
     17 package com.googlecode.android_scripting;
     18 
     19 import android.content.Context;
     20 import android.content.res.AssetManager;
     21 import android.os.Environment;
     22 
     23 import java.io.BufferedReader;
     24 import java.io.File;
     25 import java.io.FileOutputStream;
     26 import java.io.FileReader;
     27 import java.io.IOException;
     28 import java.io.InputStream;
     29 import java.io.InputStreamReader;
     30 import java.io.OutputStream;
     31 import java.lang.reflect.Method;
     32 
     33 /**
     34  * Utility functions for handling files.
     35  *
     36  * @author Damon Kohler (damonkohler (at) gmail.com)
     37  */
     38 public class FileUtils {
     39 
     40   private FileUtils() {
     41     // Utility class.
     42   }
     43 
     44   static public boolean externalStorageMounted() {
     45     String state = Environment.getExternalStorageState();
     46     return Environment.MEDIA_MOUNTED.equals(state)
     47         || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
     48   }
     49 
     50   public static int chmod(File path, int mode) throws Exception {
     51     Class<?> fileUtils = Class.forName("android.os.FileUtils");
     52     Method setPermissions =
     53         fileUtils.getMethod("setPermissions", String.class, int.class, int.class, int.class);
     54     return (Integer) setPermissions.invoke(null, path.getAbsolutePath(), mode, -1, -1);
     55   }
     56 
     57   public static boolean recursiveChmod(File root, int mode) throws Exception {
     58     boolean success = chmod(root, mode) == 0;
     59     for (File path : root.listFiles()) {
     60       if (path.isDirectory()) {
     61         success = recursiveChmod(path, mode);
     62       }
     63       success &= (chmod(path, mode) == 0);
     64     }
     65     return success;
     66   }
     67 
     68   public static boolean delete(File path) {
     69     boolean result = true;
     70     if (path.exists()) {
     71       if (path.isDirectory()) {
     72         for (File child : path.listFiles()) {
     73           result &= delete(child);
     74         }
     75         result &= path.delete(); // Delete empty directory.
     76       }
     77       if (path.isFile()) {
     78         result &= path.delete();
     79       }
     80       if (!result) {
     81         Log.e("Delete failed;");
     82       }
     83       return result;
     84     } else {
     85       Log.e("File does not exist.");
     86       return false;
     87     }
     88   }
     89 
     90   public static File copyFromStream(String name, InputStream input) {
     91     if (name == null || name.length() == 0) {
     92       Log.e("No script name specified.");
     93       return null;
     94     }
     95     File file = new File(name);
     96     if (!makeDirectories(file.getParentFile(), 0755)) {
     97       return null;
     98     }
     99     try {
    100       OutputStream output = new FileOutputStream(file);
    101       IoUtils.copy(input, output);
    102     } catch (Exception e) {
    103       Log.e(e);
    104       return null;
    105     }
    106     return file;
    107   }
    108 
    109   public static boolean makeDirectories(File directory, int mode) {
    110     File parent = directory;
    111     while (parent.getParentFile() != null && !parent.exists()) {
    112       parent = parent.getParentFile();
    113     }
    114     if (!directory.exists()) {
    115       Log.v("Creating directory: " + directory.getName());
    116       if (!directory.mkdirs()) {
    117         Log.e("Failed to create directory.");
    118         return false;
    119       }
    120     }
    121     try {
    122       recursiveChmod(parent, mode);
    123     } catch (Exception e) {
    124       Log.e(e);
    125       return false;
    126     }
    127     return true;
    128   }
    129 
    130   public static File getExternalDownload() {
    131     try {
    132       Class<?> c = Class.forName("android.os.Environment");
    133       Method m = c.getDeclaredMethod("getExternalStoragePublicDirectory", String.class);
    134       String download = c.getDeclaredField("DIRECTORY_DOWNLOADS").get(null).toString();
    135       return (File) m.invoke(null, download);
    136     } catch (Exception e) {
    137       return new File(Environment.getExternalStorageDirectory(), "Download");
    138     }
    139   }
    140 
    141   public static boolean rename(File file, String name) {
    142     return file.renameTo(new File(file.getParent(), name));
    143   }
    144 
    145   public static String readToString(File file) throws IOException {
    146     if (file == null || !file.exists()) {
    147       return null;
    148     }
    149     FileReader reader = new FileReader(file);
    150     StringBuilder out = new StringBuilder();
    151     char[] buffer = new char[1024 * 4];
    152     int numRead = 0;
    153     while ((numRead = reader.read(buffer)) > -1) {
    154       out.append(String.valueOf(buffer, 0, numRead));
    155     }
    156     reader.close();
    157     return out.toString();
    158   }
    159 
    160   public static String readFromAssetsFile(Context context, String name) throws IOException {
    161     AssetManager am = context.getAssets();
    162     BufferedReader reader = new BufferedReader(new InputStreamReader(am.open(name)));
    163     String line;
    164     StringBuilder builder = new StringBuilder();
    165     while ((line = reader.readLine()) != null) {
    166       builder.append(line);
    167     }
    168     reader.close();
    169     return builder.toString();
    170   }
    171 
    172 }
    173