之前項(xiàng)目中遇到個(gè)需求,總監(jiān)讓我們把從服務(wù)器下載下來(lái)的資源不解壓直接讀取里面的資源,這樣的話就省去了一個(gè)個(gè)校驗(yàn)資源是否正確的步驟,聽(tīng)著貌似有點(diǎn)道理。。。廢話不多說(shuō)直接上代碼。
目前我所試驗(yàn)過(guò)的可以讀取的資源有文本、圖片、xml文件。
文本:
zip包目錄結(jié)構(gòu):res/txt/data.json
文件sd卡路徑:android.os.Environment.getExternalStorageDirectory() + “/res.zip”
public static String readDataFile(String file) throws Exception { //截取路徑的文件名 res String fileName = file.substring(file.length() - 9, file.length() - 4); ZipFile zf = new ZipFile(file); InputStream in = new BufferedInputStream(new FileInputStream(file)); ZipInputStream zin = new ZipInputStream(in); ZipEntry ze; while ((ze = zin.getNextEntry()) != null) { if (ze.isDirectory()) { //Do nothing } else { if (ze.getName().equals(fileName + "/txt/data.json")) { BufferedReader br = new BufferedReader( new InputStreamReader(zf.getInputStream(ze))); String line; while ((line = br.readLine()) != null) { return line; } br.close(); } } } zin.closeEntry(); return ""; }上面方法比較簡(jiǎn)單沒(méi)什么好說(shuō)的,大家理解就行,有點(diǎn)需要注意的就是在判斷是否是想要讀取的文件的時(shí)候,這里的路徑是以zip的壓縮目錄為根目錄做比較。也就是if (ze.getName().equals(fileName + "/txt/data.json")) 這句話中的fileName 當(dāng)前值為res。最后返回讀取的內(nèi)容String就完事了。
圖片和xml文件的讀取都差不多,下面直接貼出代碼了。
圖片:
zip包目錄結(jié)構(gòu):res/pic/haha.png
文件sd卡路徑:android.os.Environment.getExternalStorageDirectory() + “/res.zip”
public static Bitmap readGuidePic(String file, String ResId) throws Exception { String fileName = file.substring(file.length() - 9, file.length() - 4); ZipFile zf = new ZipFile(file); InputStream in = new BufferedInputStream(new FileInputStream(file)); ZipInputStream zin = new ZipInputStream(in); ZipEntry ze; while ((ze = zin.getNextEntry()) != null) { if (ze.isDirectory()) { //Do nothing } else { Log.i("tag", "file - " + ze.getName() + " : " + ze.getSize() + " bytes"); if (ze.getName().equals(fileName + "/pic/haha.png")) { InputStream is = zf.getInputStream(ze); Bitmap bitmap = BitmapFactory.decodeStream(is); return bitmap; } } } zin.closeEntry(); return null; }xml文件:
zip包目錄結(jié)構(gòu):res/xml/app.xml
文件sd卡路徑:android.os.Environment.getExternalStorageDirectory() + “/res.zip”
public static InputStream readAppFile(String file) throws IOException { String fileName = file.substring(file.length() - 9, file.length() - 4); ZipFile zf = new ZipFile(file); InputStream in = new BufferedInputStream(new FileInputStream(file)); ZipInputStream zin = new ZipInputStream(in); ZipEntry ze; while ((ze = zin.getNextEntry()) != null) { if (ze.isDirectory()) { //Do nothing } else { if (ze.getName().equals(fileName + "/xml/app.xml")) { InputStream inputStream = zf.getInputStream(ze); return inputStream; } } } zin.closeEntry(); return null; }以上這篇Android 不解壓直接讀取zip包的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選