我有应用程序从url下载.zip文件,并将.zip文件中的每个文件转换为字节数组。目前我能够下载文件读取.zip文件并将整个.zip文件转换为字节,但是将.zip内的每个文件转换为字节数组。任何帮助将不胜感激。我在下面附上了我的代码:
try {
URL url = new URL(Url);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
InputStream inputStream = urlConnection.getInputStream();
dis = new DataInputStream(new BufferedInputStream(inputStream));
System.out.println("INput connection done>>>>>");
zis = new ZipInputStream(new BufferedInputStream(dis));
String targetFolder="/sdcard/";
System.out.println("zip available is"+zis.available());
int extracted = 0;
while ((entry = zis.getNextEntry()) != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
while ((count = zis.read(buffer)) != -1) {
baos.write(buffer, 0, count);
}
String filename = entry.getName();
System.out.println("File name is>>"+filename);
byte[] bytes = baos.toByteArray();
System.out.println("Bytes is >>>>"+bytes.toString());
// do something with 'filename' and 'bytes'...
zis.closeEntry();
extracted ++;
}
zis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
答案 0 :(得分:1)
您的第while ((count = zis.read(buffer)) != -1)
行循环读取整个zip文件。你想要做的是count = zis.read(buffer, 0, entry.getSize())
。这将在一个命令中将每个zip文件条目的内容转储到缓冲区中。
并且你想要使那个字节数组更大。
或者,您可以保留小缓冲区,但只需确保在主循环的每次迭代中,您只读取entry.getSize()
个字节,否则您将最终读取整个文件。
答案 1 :(得分:0)
根据Jon7的回答(如果这解决了你的问题,谁真的应该得到信用),试试这个:
while ((entry = zis.getNextEntry()) != null) {
String filename = entry.getName();
int needed = entry.getSize();
byte[] bytes = new byte[needed];
int pos = 0;
while (needed > 0) {
int read = zis.read(bytes, pos, needed);
if (read == -1) {
// end of stream -- OOPS!
throw new IOException("Unexpected end of stream after " + pos + " bytes for entry " + filename);
}
pos += read;
needed -= read;
}
System.out.println("File name is>>"+filename);
System.out.println("Bytes is >>>>"+bytes.toString());
// do something with 'filename' and 'bytes'...
zis.closeEntry();
extracted ++;
}