2
编辑:用如何访问Android中的资产?
ZipInputStream zin = new ZipInputStream(getAssets().open("totalkeys.zip"));
固定它我从一个例子,在那里它以一个字符串作为到压缩文件的路径的unzipper(解压缩)。但是由于我在我的资产中有这个文件,我不知何故需要从那里读取它......好吧,有这么多。
不幸的是它引发了我“错误/解压缩(24122):java.lang.ClassCastException:android.content.res.AssetManager $ AssetInputStream”任何想法如何解决它? )
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();
}
}
谢谢!
谢谢!还有一件事,如果我不是在一个活动中,而是在一个班级中,我如何获得上下文。见上面编辑。 – Roger
如果您在“Activity”中实例化,请为您的类创建一个自定义构造函数,该函数将一个“Context”作为参数,您可以在其中将“this”从您的活动中传递。您可以将其设置为“Context”类型的成员。如果你还可以沿着一系列构造函数或设置器传递上下文,如果需要的话。如果你真的没有从一个活动中创建,或者你没有'Context'来处理,你可能会做一些坏事,但你可以尝试调用'getApplicationContext()';该文档是在这里 - http://developer.android.com/reference/android/content/ContextWrapper.html#getApplicationContext() – SK9
我更简单一些,通过将解压缩到它自己的活动,从服务调用。见上面的编辑。现在唯一的问题是它抛出“java.lang.ClassCastException:android.content.res.AssetManager $ AssetInputStream”。 – Roger