DEADSOFTWARE

Android: improved data unpacking
[d2df-sdl.git] / android / src / org / d2df / app / CopyAssets.java
1 package org.d2df.app;
3 import android.content.Context;
4 import android.content.res.AssetManager;
5 import android.os.Environment;
7 import java.io.File;
8 import java.io.FileOutputStream;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.OutputStream;
13 import android.util.Log;
15 public class CopyAssets {
17 private static boolean ExtStorageMounted() {
18 return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
19 }
21 private static boolean ExtStorageReadonly() {
22 return Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState());
23 }
25 private static void CopyFile(InputStream in, OutputStream out)
26 throws IOException
27 {
28 byte[] buffer = new byte[1024];
29 int read;
30 while ((read = in.read(buffer)) != -1) {
31 out.write(buffer, 0, read);
32 }
33 }
35 public static void copyAssets(Context context, String prefix) {
36 AssetManager assetManager = context.getAssets();
37 String[] files = null;
38 try {
39 files = assetManager.list(prefix);
40 } catch (IOException e) {
41 Log.e("tag", "Failed to get asset file list.", e);
42 }
43 if (files != null) {
44 for (String filename : files) {
45 InputStream in = null;
46 OutputStream out = null;
47 try {
48 if (ExtStorageMounted() && !ExtStorageReadonly()) {
49 /* Get External Storage Path */
50 File f = new File(context.getExternalFilesDir(null).getAbsolutePath(), prefix);
51 if (!f.exists()) {
52 f.mkdirs();
53 }
54 File outFile = new File(context.getExternalFilesDir(null).getAbsolutePath(), prefix + "/" + filename);
55 if (!outFile.exists()) {
56 in = assetManager.open(prefix + "/" + filename);
57 out = new FileOutputStream(outFile);
58 CopyFile(in, out);
59 }
60 } else {
61 /* Get Internal Storage Path */
62 File f = new File(context.getFilesDir().getAbsolutePath(), prefix);
63 if (!f.exists()) {
64 f.mkdirs();
65 }
66 File outFile = new File(context.getFilesDir().getAbsolutePath(), prefix + "/" + filename);
67 if (!outFile.exists()) {
68 in = assetManager.open(prefix + "/" + filename);
69 out = new FileOutputStream(outFile);
70 CopyFile(in, out);
71 }
72 }
73 } catch(IOException e) {
74 Log.e("tag", "Failed to copy asset file: " + filename, e);
75 } finally {
76 if (in != null) {
77 try {
78 in.close();
79 in = null;
80 } catch (IOException e) {}
81 }
82 if (out != null) {
83 try {
84 out.flush();
85 out.close();
86 out = null;
87 } catch (IOException e) {}
88 }
89 }
90 }
91 }
92 }
94 }