java ftp zip更好的方法

时间:2012-10-11 18:28:12

标签: java ftp

我见过使用java.util.zip.ZipEntry我们可以压缩文件。

我可以压缩它,我也可以将它从一个 FTP 位置转移到其他FTP位置

 outStream.putNextEntry(new ZipEntry());
 while ((ByteRead = is.read(buf)) != -1) 
 {      
     outStream.write(buf, 0, ByteRead);
     ByteWritten += ByteRead;
 }

我也看到有一些方法FTP.sendCommand()。 但不知道如何使用它来发送命令来压缩一个FTP位置的文件并使用这种方法复制到另一个lcoation。

有人对此有任何想法吗?

1 个答案:

答案 0 :(得分:1)

我认为你分两步完成:

  1. 压缩文件并写入第一个FTP位置

    URL ftpLocation1 = new URL("ftp://url1");
    URLConnection ftpConnect1 = ftpLocation1.openConnection();
    OutputStream ftpOutStream1 = ftpConnect1.getOutputStream(); // To upload
    ftpOutStream1.putNextEntry(new ZipEntry());
    while ((ByteRead = is.read(buf)) != -1) {      
       ftpOutStream1.write(buf, 0, ByteRead);
       ByteWritten += ByteRead;
     }
    
  2. 按原样读取zip文件并写入第二个FTP位置

    InputStream ftpInputStream1 = ftpConnect1.getInputStream(); // To read back
    URL ftpLocation2 = new URL("ftp://url2");
    URLConnection ftpConnect2 = ftpLocation1.openConnection();
    OutputStream ftpOutStream2 = ftpConnect2.getOutputStream(); // To upload
    
    //read through ftpInputStream1 and write in ftpOutStream2 
    while ((ByteRead = ftpInputStream1.read(buf)) != -1) {      
       ftpOutStream2.write(buf, 0, ByteRead);
       ByteWritten += ByteRead;
     }
    
  3. 完成后,关闭所有流