how to access Assets in android?
edit: fixed it with
ZipInputStream zin = new ZipInputStream(getAssets().open("totalkeys.zip"));
I got an unzipper ( decompress ) from an example, where it takes a string as a path to a zipped file. But since I have the file in my assets, I somehow need to make to read it from there... well, got this far.
Unfortunately it throws me "ERROR/Decompress(24122): java.lang.ClassCastException: an开发者_高级运维droid.content.res.AssetManager$AssetInputStream" Any ideas how to fix it? )
public class dec extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(this, "hello, starting to unZipp!", 15500).show();
String location = Environment.getExternalStorageDirectory() + "/unzipped/";
/////////////////////////////////////////////////////////////////////
try {
AssetManager mgr = getBaseContext().getAssets();
FileInputStream fin = (FileInputStream)mgr.open("totalkeys.zip");
// throws ERROR/Decompress(24122): java.lang.ClassCastException: android.content.res.AssetManager$AssetInputStream
//FileInputStream fin = new FileInputStream(_zipFile); /// old one, that wanted a String.
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(location + ze.getName());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
}
private void dirChecker(String dir) {
String location = Environment.getExternalStorageDirectory() + "/unzipped/";
File f = new File(location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
////////////////////////////////////////////////////
finish();
}
}
Thanks!
Use your context:
InputStream is = myContext.getAssets().open("totalkeys.zip");
This returns an input stream which you can read to a buffer.
// Open the input stream
InputStream is = mContext.getAssets().open(FILE_NAME);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer))>0){
// write buffer some where, e.g. to an output stream
// as 'myOutputStream.write(buffer, 0, length);'
}
// Close the stream
try{
is.close();
} catch(IOException e){
Log.e(this.getLocalClassName().toString(), e.getMessage());
//this.getLocalClassName().toString() could be replaced with any (string) tag
}
If you're working in an activity, you can use this.getAssets()
because Activity
extends Context
. You can also pass an instance of Context
to a custom constructor if you're not working inside an activity and assign this to a member if you need it later.
精彩评论