编辑:用
修复它ZipInputStream zin = new ZipInputStream(getAssets().open("totalkeys.zip"));
我从一个示例中获得了一个解压缩器(解压缩),它将一个字符串作为压缩文件的路径。但是因为我的资产中有文件,所以我需要从那里读取它...好吧,到目前为止。
不幸的是它引发了我“错误/解压缩(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();
}
}
谢谢!
答案 0 :(得分:4)
使用您的上下文:
InputStream is = myContext.getAssets().open("totalkeys.zip");
这将返回一个输入流,您可以将其读取到缓冲区。
// 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
}
如果您正在参加某项活动,则可以使用this.getAssets()
,因为Activity
扩展了Context
。如果您没有在活动中工作,也可以将Context
的实例传递给自定义构造函数,如果以后需要,可以将其分配给成员。