SD卡中zip压缩包的解压
项目中需要从SD卡中调用文档和图片,所以从网上查阅了程序和自己动手试了试。
代码如下:
public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException { File desDir = new File(folderPath); //new一个File对象,路径为folderPath if (!desDir.exists()) //测试路径是否存在 { desDir.mkdirs(); //创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。 } ZipFile zf = new ZipFile(zipFile); //获得已存在压缩包的File对象的引用 for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) { ZipEntry entry = ((ZipEntry)entries.nextElement()); InputStream in = zf.getInputStream(entry); String str = folderPath + File.separator + entry.getName(); //separator为路径的标识"/" //判断是否为文件夹.若为文件夹则不处理 String name = entry.getName(); if(name.endsWith(File.separator)) { continue; } str = new String(str.getBytes("8859_1"), "GB2312"); //转码,暂时不知道为什么这么转 File desFile = new File(str); if (!desFile.exists()) { File fileParentDir = desFile.getParentFile(); if (!fileParentDir.exists()) { fileParentDir.mkdirs(); //创建父文件夹 } boolean isCreate=desFile.createNewFile(); if(isCreate) { System.out.println("创建成功"); }else { System.out.println("创建失败"); } } OutputStream out = new FileOutputStream(desFile); //输出文件 byte buffer[] = new byte[BUFF_SIZE]; int realLength; while ((realLength = in.read(buffer)) > 0) { out.write(buffer, 0, realLength); } in.close(); out.close(); } }
收获如下:
1>对File对象有了进一步的掌握,尤其是它的构造器不同所new的对象的不同。
2>了解了File几个方法的使用。
3>对ZipFile类的使用方法有了初步了解。
4>对流有了进一步的掌握。
在实践过程中,我们应该多查阅官方文档,看些正规代码的书写,多想想为什么,为什么类的构造器这样定义,为什么有这些方法,在没有了解全部的方法之前,如果是你,你会在该类中添加什么方法。多动脑思考,透过现象看本质,我们就会对Android的魅力所吸引。
总之,多动手,少BB。