2012-06-26 77 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

這不會備份/複製文件,它移動一個文件。這不是這個問題的關鍵。 –

相關問題