2011-09-04 64 views
2

我只是想知道如何使用java压缩网上的文件,当然。Java - 从网站压缩文件?

我知道如何为硬盘驱动器上的目录做到这一点,而不是网站:

ZipFile zipfile = new ZipFile("C:/Documents and Settings/User/desktop/something.file"); 

非常感谢你。

+0

你是什么意思“在网上的文件”?就像你通过一个'HttpUrlConnection'从一个删除网站收到的东西? –

+0

基本上,不是压缩位于硬盘驱动器上的文件 - 我希望它从网络服务器压缩文件,给定http://blahblablah.com/file.txt的地址(这是我的意思是“从网络“)。 – john

+1

如果你的意思是你想在Web服务器上压缩文件并发送到你的程序已经压缩,那么你不能。服务器需要为您做这件事,并将压缩文件发送给您。你的问题并不清楚。 –

回答

0

这是相同的,但你必须使用两个方法:

String filePath = getServletContext().getRealPath("/WEB-INF/your_folder/your_file"); 

filepath是绝对的文件系统路径(C:/.../ WEB-INF /您的文件夹/ your_file)

+0

呃,那不是我想要做的。显然该文件需要是JAR文件?不过,是不是有更简单的方法来从网络服务器压缩文件?而不是从你的驱动器。 – john

1

所以我认为你要下载和压缩一个文件。这是两个不同的任务,所以你需要两样东西做到这一点:

  • 东西,从网络上下载的文件
  • 东西把它压缩成zip文件

我建议你使用Apache HttpComponents下载该文件,Apache Compress将其压缩。

然后代码会去这样的事情...

// 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(); 
    } 

它是如何工作的? HttpComponents正在获取文件的InputStream,并且Compress正在提供OutputStream。那么你只是从一个流复制到另一个流。这就像魔术一样!