如何将FTP服务器上的文件复制到目录中的Java在同一台服务器上?(How to copy a fi

2019-06-25 18:44发布

我使用的Apache共享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();
    }

}

编辑代码:还有一个问题,当我备份的压缩文件,备份,编辑文件已损坏。

是否有任何身体知道的原因吧?

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

}

Answer 1:

如果您使用的是Apache公地网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

希望这可以帮助你..



Answer 2:

试试这个方法,

我使用Apache的库。

ftpClient.rename(从,到),会更容易,我在下面在哪里添加ftpClient.rename(从,到)的代码已经提到。

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

// $$$$$$$$$$$$$$$$$$$$$$$$$$$$$增加了备份这里$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$ //

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

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

// $$$$$$$$$$$$$$$$$$$$$$$$$$$$$增加了备份这里$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$ //

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

    }


Answer 3:

有复制了FTP协议的远程文件没有标准的方式。 一些FTP服务器支持这虽然专有或非标准的扩展。


所以,如果你很幸运,你的服务器的ProFTPD与mod_copy模块 ,你可以使用FTP.sendCommand发出这两个命令:

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

第二种可能性是,你的服务器允许执行任意shell命令。 这甚至不太常见。 如果您的服务器支持这一点,你可以用SITE EXEC命令:

SITE EXEC cp -p sourcepath targetpath

另一个解决方法是打开到FTP服务器的第二连接,使服务器通过管道到活动模式数据连接的被动模式数据连接的文件上传到自身。 该解决方案(在PHP虽然)中所示的实现FTP文件复制到同一个FTP另一个地方 。


如果没有这样的作品,你所能做的就是将文件下载到本地临时位置并重新上传回的目标位置。 这就是由@ RP-答案显示 。


另请参见FTP文件复制到同一FTP另一个地方 。



Answer 4:

要在同一台服务器(移动)的备份,你可以使用:

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


文章来源: How to copy a file on the FTP server to a directory on the same server in Java?