2012-06-26 73 views
10

我正在使用Apache Commons FTP上传文件。在上传之前,我想检查服务器上是否已存在该文件,并将其备份到同一台服务器上的备份目录中。如何将ftp服务器上的文件复制到java中同一服务器上的目录中?

有谁知道如何将文件从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(); 
    } 

} 
+0

你不明白什么?如果您知道源路径和远程路径,您可以打开文件进行读取(使用缓冲区)并写入远程路径。你也可以使用os特定的api来处理文件。 –

+0

文件类型是FTPFile。我如何读写缓冲区? 你是否喜欢'FileInputStream in = new FileInputStream(file);' – itro

+0

http://www.dreamincode.net/forums/topic/32031-ftp-in-java-using-apache-commons-net/ –

回答

16

如果您使用的是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. 
} 

,经过文档,并且不会有客户端的实现之间没有太大的变化。

UPDATE:

上面的方法将文件移动到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

用你的解决方案'ftpClient.rename(from,to);'我可以重新命名它,但仍然停留在同一个目录中,而不是我想要的(备份目录)。 我该如何解决它?我如何获得备份路径?第二个参数的正确路径是什么,如果我想将文件复制到buckup目录? 我有根目录中的所有文件位于那里和备份目录,我在根目录下创建它。 – itro

+0

类似'ftpClient.rename(“/ root/your_file.txt”,“/root/backup/your_file_bak.txt”);'。有一点需要注意的是,它从'from'目录移动到''目录。你不会再把它放在'from'目录中。 –

+0

ohhhhhhhhh不,我想只是它的一个副本不移动它备份。 – itro

1

尝试这种方式,

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

    } 
+0

我应该检查服务器中是否存在文件,然后进行备份然后上传文件。我认为你在这里做了别的 – itro

+0

如果(结果)是在文件成功存储在服务器上后执行的块,再次正确地再次查看它..... –

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

这不会备份/复制文件,它移动一个文件。这不是这个问题的关键。 –

相关问题