使用zip边压缩边下载
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipHttpInputStream extends InputStream {
private List<File> list = new ArrayList<>();
private ByteArrayOutputStream bos = new ByteArrayOutputStream();
private ZipOutputStream zipOutputStream = new ZipOutputStream(bos);
private FileInputStream fileInputStream = null;
private int fileIndex = 0;
private boolean readFinish = false;
private byte[] curByte = new byte[0];
private int readPos = 0;
public ZipHttpInputStream(List<File> list) {
this.list = list;
nextFile();
}
public boolean readFile() throws IOException {
if (readFinish) {
return false;
}
byte[] buffer = new byte[1024 * 10];
int len = fileInputStream.read(buffer);
if (len < 0) {
if (fileIndex >= list.size()) {
zipOutputStream.closeEntry();
zipOutputStream.close();
curByte = bos.toByteArray();
readFinish = true;
return true;
}
nextFile();
len = fileInputStream.read(buffer);
}
zipOutputStream.write(buffer, 0, len);
curByte = bos.toByteArray();
bos.reset();
return true;
}
public void nextFile() {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
File file = list.get(fileIndex);
fileIndex++;
fileInputStream = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(file.getName());
zipOutputStream.putNextEntry(zipEntry);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public int read() throws IOException {
return -1;
}
@Override
public int read(byte b[], int off, int len) throws IOException {
Objects.checkFromIndexSize(off, len, b.length);
int count = curByte.length;
if (readPos >= count) {
if (!readFile()) {
return -1;
}
readPos = 0;
count = curByte.length;
}
int avail = count - readPos;
if (len > avail) {
len = avail;
}
if (len <= 0) {
return 0;
}
System.arraycopy(curByte, readPos, b, off, len);
readPos += len;
return len;
}
}