开发者

Java - Zipping files from websites?

开发者 https://www.devze.com 2023-04-02 02:58 出处:网络
I just wanted to know how can I zip a file on the web using java, of course. I know how to do this for directories on the hard drive, but not for websites:

I just wanted to know how can I zip a file on the web using java, of course.

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");

Th开发者_JAVA技巧ank 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:

  • something to download the file from the web
  • something to compress it into a zip file

I suggest that you use Apache HttpComponents to download the file, and Apache Compress to compress it.

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. 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)


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号