编辑:修复它
ZipInputStream zin = new ZipInputStream(getAssets().open("totalkeys.zip"));
Run Code Online (Sandbox Code Playgroud)
我从一个例子中得到了一个解压缩器( decompress ),它把一个字符串作为一个压缩文件的路径。但是由于我的资产中有该文件,所以我需要从那里读取它......好吧,到目前为止。
不幸的是它抛出我“错误/解压缩(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();
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
使用您的上下文:
InputStream is = myContext.getAssets().open("totalkeys.zip");
Run Code Online (Sandbox Code Playgroud)
这将返回一个可以读取到缓冲区的输入流。
// 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
}
Run Code Online (Sandbox Code Playgroud)
如果您正在从事一项活动,则可以使用this.getAssets()因为Activityextends Context。Context如果您不在活动中工作,也可以将 的实例传递给自定义构造函数,并在以后需要时将其分配给成员。
| 归档时间: |
|
| 查看次数: |
13327 次 |
| 最近记录: |