java 구현 서버 파일 압축 zip 및 다운로드 예시 (압축하면서 다운로드)
/**
*
* mySocket Socket
* @param file
* @param fileName
* @throws IOException
*/
private void down(File file, String fileName) throws IOException {
OutputStream outputStream = mySocket.getOutputStream();
StringBuffer sb = new StringBuffer("HTTP/1.1 200 OK\r
");
sb.append("Server: java/1.1\r
");
sb.append("Content-Type:application/octet-stream;charset=UTF-8\r
");
//sb.append("User-Agent: Mozilla/4.0 (compatible;MSIE6.0;Windows NT 5.0)\r
");
sb.append("Content-Disposition: attachment; filename=" + fileName
+ "\r
");
sb.append("Transfer-Encoding: chunked\r
");
sb.append("Connection: Keep-Alive\r
\r
");
outputStream.write(sb.toString().getBytes());
outputStream.flush();
ZipCompressor zipCompressor = new ZipCompressor(new MyOutputStream(
outputStream));
zipCompressor.compress(file);
System.out.println("zip end");
System.out.println("write '0\\r\
\\r\
'");
outputStream.write("0\r
\r
".getBytes());//Transfer-Encoding: chunked
outputStream.flush();
outputStream.close();
System.out.println("download stop");
try {
mySocket.close();
} catch (Throwable t) {
}
}
package cn.liangjintang.webserver.zipFile;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipCompressor {
static final int BUFFER = 8192;
private OutputStream outputStream;
public ZipCompressor(MyOutputStream outputStream) {
this.outputStream=outputStream;
}
public void compress(File file) {
if (!file.exists())
throw new RuntimeException(file.getAbsolutePath() + " !");
try {
CheckedOutputStream cos = new CheckedOutputStream(outputStream,
new CRC32());
ZipOutputStream out = new ZipOutputStream(cos);
String basedir = "";
compress(file, out, basedir);
out.close();// , zip , zip . , outputStream.close()
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void compress(File file, ZipOutputStream out, String basedir) {
//
if (file.isDirectory()) {
System.out.println(" :" + basedir + file.getName());
this.compressDirectory(file, out, basedir);
} else {
System.out.println(" :" + basedir + file.getName());
this.compressFile(file, out, basedir);
}
}
//
private void compressDirectory(File dir, ZipOutputStream out, String basedir) {
if (!dir.exists())
return;
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
/** */
compress(files[i], out, basedir + dir.getName() + "/");
}
}
//
private void compressFile(File file, ZipOutputStream out, String basedir) {
if (!file.exists()) {
return;
}
try {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
ZipEntry entry = new ZipEntry(basedir + file.getName());
out.putNextEntry(entry);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
bis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
package cn.liangjintang.webserver.zipFile;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class MyOutputStream extends FilterOutputStream {
public MyOutputStream(OutputStream out) {
super(out);
}
final byte[] oneBytes = "1\r
".getBytes();
final byte[] rnBytes = "\r
".getBytes();
public void write(int b) throws IOException {
out.write(oneBytes);// 1+CRLF
out.write(b);//
out.write(rnBytes);//CRLF
}
public void write(byte[] b) throws IOException {
out.write(Integer.toHexString(b.length).getBytes());// ,
out.write(rnBytes);//CRLF
out.write(b);//
out.write(rnBytes);//CRLF
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(Integer.toHexString(len - off).getBytes());// ,
out.write(rnBytes);//CRLF
out.write(b, off, len);//
out.write(rnBytes);//CRLF
}
/**
* , OutputStream , <br/>
* ( Transfer-Encoding: chunked )
*/
public void close() throws IOException {
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
38. Java의 Leetcode 솔루션텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.