读取Zip存档中的文件,并将其内容放入Android中的String中

这是我的第一个问题,虽然我已经使用了Stack Overflow的很多技巧。 但对于这种情况,我还没有找到解决方案。

下面是这种情况:我有一个压缩文件,我想读取一个特定的文件并将其内容放入一个String变量中,该变量将被返回并放入Android中的TextView中。 我不希望将文件写入sdcard,我只想执行内存操作。

例如,在db.zip中我有一个名为packed.txt的文件,其内容为“Stackáéç”。 我方法中返回的String显示“83 116 97 99 107 32 195 161 32(…)”,这些是字符的UTF-8值。 到目前为止,我尝试将”转换为人类可读的forms,但没有成功。 尝试过InputStreamReader,但我无法正确使用它。 我的源代码如下。

import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import android.util.Log; /** * * @author jon */ public class Decompress { private String _zipFile; private String _location; public Decompress(String zipFile, String location) { _zipFile = zipFile; _location = location; _dirChecker(""); } public String unzip(String desiredFile) { String strUnzipped = ""; try { FileInputStream fin = new FileInputStream(_zipFile); 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()); /**** Changes made below ****/ if (ze.getName().toString().equals(desiredFile)) { byte[] bytes = new byte[(int) ze.getSize()]; if (zin.read(bytes, 0, bytes.length) == bytes.length) { strUnzipped = new String(bytes, "UTF-8"); } else { strUnzipped = "Read error..."; } /*** REMOVED if (ze.getName() == desiredFile) { for (int c = zin.read(); c != -1; c = zin.read()) { strUnzipped += c; //fout.write(c); } */ } zin.closeEntry(); //fout.close(); } } zin.close(); } catch(Exception e) { Log.e("Decompress", "unzip", e); } return strUnzipped; } private void _dirChecker(String dir) { File f = new File(_location + dir); if(!f.isDirectory()) { f.mkdirs(); } } } 

对不起,我最初的post….跑过你的段落,说明你试过这个。

您可以使用“UTF-8”字符集创建InputStreamReader,它会自动将输入数据转换为正确的字符。

 while ((ze = zin.getNextEntry()) != null) { Log.v("Decompress", "Unzipping " + ze.getName()); if(ze.isDirectory()) { _dirChecker(ze.getName()); } else { if (ze.getName() == desiredFile) { byte[] bytes= new byte[ze.getSize()]; zin.read(bytes, 0, bytes.length); strUnzipped= new String( bytes, "UTF-8" ); /* Removing this as it is easier to just read all the bytes in at once InputStreamReader isr= new InputStreamReader(zin, "UTF-8"); char c= 0; for (char c = isr.read(); c != -1; c = isr.read()) { strUnzipped += c; } */ } zin.closeEntry(); } } 

请尝试以上操作,看看它是如何工作的。

为什么不将它们加载到字节数组中并使用新的String(byte [])或使用StringBuilder?

 StringBuilder sb = new StringBuilder(); for (int c = zin.read(); c != -1; c = zin.read()) { sb.append((byte)c); } ... return sb.toString();