如何将FTP服务器上的文件复制到Java中同一服务器上的目录?

时间:2012-06-26 07:02:08

标签: java ftp client-server ftp-client apache-commons-net

我正在使用Apache Commons FTP上传文件。在上传之前,我想检查服务器上是否已存在该文件,并从该服务器备份到同一服务器上的备份目录。

有谁知道如何将文件从FTP服务器复制到同一台服务器上的备份目录?

public static void uploadWithCommonsFTP(File fileToBeUpload){
    FTPClient f = new FTPClient();
    FTPFile backupDirectory;
    try {
        f.connect(server.getServer());
        f.login(server.getUsername(), server.getPassword());
        FTPFile[] directories = f.listDirectories();
        FTPFile[] files = f.listFiles();
        for(FTPFile file:directories){
            if (!file.getName().equalsIgnoreCase("backup")) {
                backupDirectory=file;
            } else {
               f.makeDirectory("backup");
            }
        }
        for(FTPFile file: files){
            if(file.getName().equals(fileToBeUpload.getName())){
                //copy file to backupDirectory
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}

编辑代码:仍有问题,当我备份zip文件时,备份文件已损坏。

是否有人知道原因?

 public static void backupUploadWithCommonsFTP(File fileToBeUpload) {
    FTPClient f = new FTPClient();
    boolean backupDirectoryExist = false;
    boolean fileToBeUploadExist = false;
    FTPFile backupDirectory = null;
    try {
        f.connect(server.getServer());
        f.login(server.getUsername(), server.getPassword());
        FTPFile[] directories = f.listDirectories();
        // Check for existence of backup directory
        for (FTPFile file : directories) {
            String filename = file.getName();
            if (file.isDirectory() && filename.equalsIgnoreCase("backup")) {
                backupDirectory = file;
                backupDirectoryExist = true;
                break;
            }
        }
        if (!backupDirectoryExist) {
            f.makeDirectory("backup");
        }
        // Check if file already exist on the server
        f.changeWorkingDirectory("files");
        FTPFile[] files = f.listFiles();
        f.changeWorkingDirectory("backup");
        String filePathToBeBackup="/home/user/backup/";
        String prefix;
        String suffix;
        String fileNameToBeBackup;
        FTPFile fileReadyForBackup = null;
        f.setFileType(FTP.BINARY_FILE_TYPE);
        f.setFileTransferMode(FTP.BINARY_FILE_TYPE);
        for (FTPFile file : files) {
            if (file.isFile() && file.getName().equals(fileToBeUpload.getName())) {
                prefix = FilenameUtils.getBaseName(file.getName());
                suffix = ".".concat(FilenameUtils.getExtension(file.getName()));
                fileNameToBeBackup = prefix.concat(Calendar.getInstance().getTime().toString().concat(suffix));
                filePathToBeBackup = filePathToBeBackup.concat(fileNameToBeBackup);
                fileReadyForBackup = file;
                fileToBeUploadExist = true;
                break;
            }
        }
        // If file already exist on the server create a backup from it otherwise just upload the file.
        if(fileToBeUploadExist){
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            f.retrieveFile(fileReadyForBackup.getName(), outputStream);
            InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
            if(f.storeUniqueFile(filePathToBeBackup, is)){
                JOptionPane.showMessageDialog(null, "Backup succeeded.");
                f.changeWorkingDirectory("files");
                boolean reply = f.storeFile(fileToBeUpload.getName(), new FileInputStream(fileToBeUpload));
                if(reply){
                    JOptionPane.showMessageDialog(null,"Upload succeeded.");
                }else{
                    JOptionPane.showMessageDialog(null,"Upload failed after backup.");
                }
            }else{
                JOptionPane.showMessageDialog(null,"Backup failed.");
            }
        }else{
            f.changeWorkingDirectory("files");
            f.setFileType(FTP.BINARY_FILE_TYPE);
            f.enterLocalPassiveMode();
            InputStream inputStream = new FileInputStream(fileToBeUpload);
            ByteArrayInputStream in = new ByteArrayInputStream(FileUtils.readFileToByteArray(fileToBeUpload));
            boolean reply = f.storeFile(fileToBeUpload.getName(), in);
            System.out.println("Reply code for storing file to server: " + reply);
            if(!f.completePendingCommand()) {
                f.logout();
                f.disconnect();
                System.err.println("File transfer failed.");
                System.exit(1);
            }
            if(reply){

                JOptionPane.showMessageDialog(null,"File uploaded successfully without making backup." +
                        "\nReason: There wasn't any previous version of this file.");
            }else{
                JOptionPane.showMessageDialog(null,"Upload failed.");
            }
        }
        //Logout and disconnect from server
        in.close();
        f.logout();
        f.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

4 个答案:

答案 0 :(得分:19)

如果您正在使用apache commons net FTPClient,则可以使用直接方法将文件从一个位置移动到另一个位置(如果user具有适当的权限)。

ftpClient.rename(from, to);

或者,如果您熟悉ftp commands,则可以使用

之类的内容
ftpClient.sendCommand(FTPCommand.yourCommand, args);
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
     //command successful;
} else {
     //check for reply code, and take appropriate action.
}

如果您正在使用任何其他客户端,请查看文档,客户端实现之间不会有太多变化。

<强>更新

上面的方法将文件移动到to目录,即该文件不再存在于from目录中。基本上,ftp协议意味着从local <-> remoteremote <-> other remote传输文件,但不能在服务器中传输。

这里的工作会更简单,将完整的文件发送到本地InputStream并将其作为备份目录中的新文件写回服务器。

获取完整文件,

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ftpClient.retrieveFile(fileName, outputStream);
InputStream is = new ByteArrayInputStream(outputStream.toByteArray());

现在,将此流存储到备份目录。首先,我们需要将工作目录更改为备份目录。

// assuming backup directory is with in current working directory
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//binary files
ftpClient.changeWorkingDirectory("backup");
//this overwrites the existing file
ftpClient.storeFile(fileName, is);
//if you don't want to overwrite it use storeUniqueFile

希望这可以帮助你..

答案 1 :(得分:1)

试试这种方式,

我正在使用apache的库。

ftpClient.rename(from,to)会让它变得更容易,我在下面的代码中提到过 在哪里添加ftpClient.rename(from,to)。

public void goforIt(){


        FTPClient con = null;

        try
        {
            con = new FTPClient();
            con.connect("www.ujudgeit.net");

            if (con.login("ujud3", "Stevejobs27!!!!"))
            {
                con.enterLocalPassiveMode(); // important!
                con.setFileType(FTP.BINARY_FILE_TYPE);
                String data = "/sdcard/prerakm4a.m4a";
                ByteArrayInputStream(data.getBytes());
                FileInputStream in = new FileInputStream(new File(data));
                boolean result = con.storeFile("/Ads/prerakm4a.m4a", in);
                in.close();
                if (result) 
                       {
                            Log.v("upload result", "succeeded");

// $$$$$$$$$$$$$$$$$$$$$$$$$$$添加备份Here $$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$ //

                   // Now here you can store the file into a backup location

                  // Use ftpClient.rename(from, to) to place it in backup

// $$$$$$$$$$$$$$$$$$$$$$$$$$$添加备份Here $$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$ //

                       }
                con.logout();
                con.disconnect();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }   

    }

答案 2 :(得分:0)

没有通过FTP协议复制远程文件的标准方法。但是某些FTP服务器为此支持专有或非标准扩展。


因此,如果您很幸运您的服务器是带有mod_copy module的ProFTPD,则可以使用FTP.sendCommand发出以下两个命令:

f.sendCommand("CPFR sourcepath");
f.sendCommand("CPTO targetpath");

第二种可能性是您的服务器允许您执行任意的Shell命令。这很少见。如果您的服务器支持此功能,则可以使用SITE EXEC命令:

SITE EXEC cp -p sourcepath targetpath

另一个解决方法是通过将被动模式数据连接管道传输到主动模式数据连接,打开与FTP服务器的第二个连接,并使服务器将文件上传到自身。 FTP copy a file to another place in same FTP中显示了此解决方案的实现(尽管在PHP中)。


如果这两种方法均无效,则您只能将文件下载到本地临时位置,然后将其重新上传回目标位置。这就是answer by @RP- shows


另请参阅FTP copy a file to another place in same FTP

答案 3 :(得分:-1)

要在同一服务器上备份(移动),您可以使用:

String source="/home/user/some";
String goal  ="/home/user/someOther";
FTPFile[] filesFTP = cliente.listFiles(source);

clientFTP.changeWorkingDirectory(goal);  // IMPORTANT change to final directory

for (FTPFile f : archivosFTP) 
   {
    if(f.isFile())
       {
        cliente.rename(source+"/"+f.getName(), f.getName());
       }
   }