通过url获取流将该流以zip形式输出
时间: 2023-08-22 07:05:13 浏览: 129
FFMPEG USB摄像头RTMP推流.zip
可以使用Java中的ZipOutputStream类将一个流以zip形式输出。可以按照以下步骤实现:
1. 通过URL获取输入流
```java
URL url = new URL("http://example.com/file.zip");
InputStream in = url.openStream();
```
2. 创建ZipOutputStream并设置输出流
```java
ZipOutputStream out = new ZipOutputStream(new FileOutputStream("output.zip"));
```
3. 将获取到的流写入到ZipOutputStream中
```java
out.putNextEntry(new ZipEntry("file.zip"));
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
```
4. 关闭输入流和ZipOutputStream
```java
in.close();
out.closeEntry();
out.close();
```
完整示例代码如下:
```java
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.com/file.zip");
InputStream in = url.openStream();
ZipOutputStream out = new ZipOutputStream(new FileOutputStream("output.zip"));
out.putNextEntry(new ZipEntry("file.zip"));
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
in.close();
out.closeEntry();
out.close();
}
}
```
运行该程序后,会将获取到的流以zip形式输出到当前目录下的output.zip文件中。
阅读全文