Skip to content

Instantly share code, notes, and snippets.

@IvanWooll
Created August 27, 2015 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IvanWooll/3495e61cd6f3173bf06f to your computer and use it in GitHub Desktop.
Save IvanWooll/3495e61cd6f3173bf06f to your computer and use it in GitHub Desktop.
work in progress class for copying files from asset folder
package theappdevelopers.ocrreceiptscanner;
import android.content.Context;
import android.content.res.AssetManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by ivanwooll on 27/08/15.
*/
public class AssetUtils {
public static boolean copyAssetFolder(Context context, String fromAssetPath, String toPath) {
AssetManager assetManager = getAssetManager(context);
checkPath(toPath);
try {
String[] files = assetManager.list(fromAssetPath);
new File(toPath);
boolean res = true;
for (String file : files)
if (file.contains("."))
res &= copyAsset(context, fromAssetPath + "/" + file, toPath + "/" + file);
else
res &= copyAssetFolder(context, fromAssetPath + "/" + file, toPath + "/" + file);
return res;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* copies a named file from the assets folder to the app internal "Files" directory ('data/data/packagename')
*
* @param context
* @param fromAssetPath
* @param toPath
*/
public static boolean copyAsset(Context context, String fromAssetPath, String toPath) {
toPath = context.getFilesDir().getAbsolutePath() + "/" + toPath;
checkPath(toPath);
AssetManager assetManager = getAssetManager(context);
InputStream in;
OutputStream out;
try {
in = assetManager.open(fromAssetPath);
new File(toPath).createNewFile();
out = new FileOutputStream(toPath);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static AssetManager getAssetManager(Context context) {
return context.getAssets();
}
/**
* check directory(s) exist and create if not
*
* @param fullFilePath
*/
private static void checkPath(String fullFilePath) {
File file = new File(getDirs(fullFilePath));
if (!file.exists()) {
file.mkdirs();
}
}
/**
* @param path
* @return a String representing the full path up to (but not including) the last occurence of '/'
*/
private static String getDirs(String path) {
if (!path.contains("/")) {
return path;
}
int end = path.lastIndexOf('/');
return path.substring(0, end);
}
private static void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment