压缩存在于一个FTP位置的文件并直接复制到另一个FTP位置

时间:2012-10-17 11:21:51

标签: java ftp zip

我想创建存在于一个ftp位置的文件的zip文件,并将此zip文件复制到其他ftp位置,而不在本地保存。

我能够处理小尺寸的文件。它适用于1 mb等小尺寸文件

但是如果文件大小很大,如100 MB,200 MB,300 MB那么它给出错误,

java.io.FileNotFoundException: STOR myfile.zip : 550 The process cannot access the 
file because it is being used by another process. 
at sun.net.ftp.FtpClient.readReply(FtpClient.java:251)
at sun.net.ftp.FtpClient.issueCommand(FtpClient.java:208)
at sun.net.ftp.FtpClient.openDataConnection(FtpClient.java:398) 
at sun.net.ftp.FtpClient.put(FtpClient.java:609)

我的代码是

    URLConnection  urlConnection=null;
    ZipOutputStream zipOutputStream=null;
    InputStream inputStream = null;
    byte[] buf;
    int ByteRead,ByteWritten=0; 
    ***Destination where file will be zipped***
    URL url = new URL("ftp://" + ftpuser+ ":" + ftppass + "@"+ ftppass + "/" +
            fileNameToStore + ";type=i");
    urlConnection=url.openConnection();         
    OutputStream outputStream = urlConnection.getOutputStream();
    zipOutputStream = new ZipOutputStream(outputStream);
    buf = new byte[size];
    for (int i=0; i<li.size(); i++) 
    {
        try
        {
            ***Souce from where file will be read***
            URL u= new URL((String)li.get(i));  // this li has values http://xyz.com/folder
            /myPDF.pdf
            URLConnection uCon = u.openConnection();
            inputStream = uCon.getInputStream();
            zipOutputStream.putNextEntry(new ZipEntry((String)li.get(i).substring((int)li.get(i).lastIndexOf("/")+1).trim()));
            while ((ByteRead = inputStream .read(buf)) != -1)    
            {       
                zipOutputStream.write(buf, 0, ByteRead);
                ByteWritten += ByteRead;
            }
            zipOutputStream.closeEntry();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    if (inputStream  != null) {
        try { 
            inputStream .close(); 
        } 
        catch (Exception e) { 
            e.printStackTrace();
        }
    }
    if (zipOutputStream != null) {
        try { 
            zipOutputStream.close(); 
        } catch (Exception e){
            e.printStackTrace(); 
        }     
    }

任何人都可以告诉我如何避免此错误并处理大文件

2 个答案:

答案 0 :(得分:1)

这与文件大小无关;如错误所示,您无法替换该文件,因为其他进程当前正在锁定它。

你经常看到大文件的原因是因为传输这些文件需要更长的时间,因此并发访问的可能性更高。

因此,唯一的解决方案是确保在您尝试传输文件时没有人使用该文件。祝你好运。

可能的其他解决方案:

  1. 请勿在服务器上使用Windows。
  2. 以临时名称传输文件,并在文件完成后重命名。这样,其他进程将看不到不完整的文件。总是一件好事。
  3. 使用rsync而不是再次发明轮子。

答案 1 :(得分:0)

当天,在我们拥有网络安全之前,有一些FTP服务器允许第三方转移。您可以使用特定于站点的命令并直接将文件发送到另一个FTP服务器。那些日子已经一去不回。叹息。

好吧,也许不久就没了。某些FTP服务器支持代理命令。这里有一个讨论:http://www.math.iitb.ac.in/resources/manuals/Unix_Unleashed/Vol_1/ch27.htm