[英]Java - Zipping files from websites?
I just wanted to know how can I zip a file on the web using java, of course. 当然,我只是想知道如何使用Java将文件压缩到Web上。
I know how to do this for directories on the hard drive, but not for websites: 我知道如何对硬盘驱动器上的目录执行此操作,但对于网站却不行:
ZipFile zipfile = new ZipFile("C:/Documents and Settings/User/desktop/something.file");
Thank you very much. 非常感谢你。
So I take it that you want to download and compress a file. 因此,我认为您要下载并压缩文件。 That's two different tasks, so you need two things to do it:
那是两个不同的任务,因此您需要做两件事:
I suggest that you use Apache HttpComponents to download the file, and Apache Compress to compress it. 我建议您使用Apache HttpComponents下载文件,并使用Apache Compress压缩文件。
Then the code would go something like this... 然后代码会像这样...
// Obtain reference to file
HttpGet httpGet = new HttpGet("http://blahblablah.com/file.txt");
HttpResponse httpResponse = httpclient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
// Create the output ZIP file
ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile);
try {
// Write a file header in the .zip file
ArchiveEntry entry = new ZipArchiveEntry("file.txt");
zip.putArchiveEntry(entry);
// Download the file and write it to a compressed file
IOUtils.copy(httpEntity.getContent(), zip);
// The file is now written
zip.closeArchiveEntry();
} finally {
// Ensure output file is closed
zip.close();
}
How does it work? 它是如何工作的? HttpComponents is obtaining an
InputStream
of the file, and Compress is providing an OutputStream
. HttpComponents正在获取文件的
InputStream
,而Compress正在提供OutputStream
。 Then you're just copying from one stream into the other. 然后,您只是从一个流复制到另一个流。 It's like magic!
就像魔术!
It's the same but you have to use a couple of methods: 一样,但是您必须使用两种方法:
String filePath = getServletContext().getRealPath("/WEB-INF/your_folder/your_file");
filepath is the absolute filesystem path (C:/.../WEB-INF/your_folder/your_file) filepath是绝对文件系统路径(C:/.../ WEB-INF / your_folder / your_file)
By 'zip a file on the web' it sounds like you mean doing so programatically within code in a web or application server. 通过“在网络上压缩文件”,这听起来像是您在网络或应用程序服务器中的代码中以编程方式执行此操作。
This page may help. 此页面可能会有所帮助。 It discusses how to use the java.util.zip package: http://java.sun.com/developer/technicalArticles/Programming/compression/
它讨论了如何使用java.util.zip软件包: http : //java.sun.com/developer/technicalArticles/Programming/compression/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.