2012-06-26 26 views
10

Tôi đang sử dụng Apache Commons FTP để tải lên một tệp. Trước khi tải lên, tôi muốn kiểm tra xem tệp đã tồn tại trên máy chủ chưa và sao lưu từ tệp đó vào thư mục sao lưu trên cùng một máy chủ.Làm thế nào để sao chép một tập tin trên máy chủ FTP đến một thư mục trên cùng một máy chủ trong java?

Có ai biết làm thế nào để sao chép một tập tin từ một máy chủ ftp vào một thư mục sao lưu trên cùng một máy chủ?

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

} 

đang được sửa đổi: vẫn còn là một vấn đề, khi tôi file zip sao lưu, tập tin sao lưu-ed là hỏng.

Có bất kỳ cơ thể biết lý do cho nó?

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

bạn không hiểu điều gì? nếu bạn biết đường dẫn nguồn và đường dẫn distanation bạn chỉ có thể mở tập tin để đọc (với bộ đệm) và viết trên đường dẫn. bạn cũng có thể sử dụng api cụ thể của os để đối phó với các tập tin. –

+0

Loại tệp là FTPFile. làm thế nào tôi có thể đọc và viết trong bộ đệm? bạn có nghĩa là như 'FileInputStream in = new FileInputStream (tệp); ' – itro

+0

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

Trả lời

16

Nếu bạn đang sử dụng commons apache ròng FTPClient, có một phương pháp trực tiếp để di chuyển một tập tin từ một địa điểm đi nơi khác (nếu user có quyền truy cập thích hợp).

ftpClient.rename(from, to); 

hay, Nếu bạn đã quen thuộc với ftp commands, bạn có thể sử dụng giống như

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

Nếu bạn đang sử dụng bất kỳ khách hàng khác, đi qua các tài liệu, Có wont có thay đổi nhiều giữa hiện thực khách hàng.

UPDATE:

Trên phương pháp di chuyển các tập tin vào thư mục to, tức là, các tập tin sẽ không có mặt ở đó trong from thư mục nữa. Về cơ bản, giao thức ftp có nghĩa là chuyển các tệp từ local <-> remote hoặc remote <-> other remote nhưng không được chuyển với máy chủ.

Công việc ở đây, sẽ đơn giản hơn, tải tệp hoàn chỉnh về địa chỉ InputStream và ghi lại tệp đó vào máy chủ dưới dạng tệp mới trong thư mục sao lưu.

để có được đầy đủ hồ sơ,

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

bây giờ, cửa hàng dòng này vào thư mục sao lưu. Đầu tiên chúng ta cần thay đổi thư mục làm việc thành thư mục sao lưu.

// 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 

Hy vọng điều này sẽ giúp bạn ..

+1

Với giải pháp của bạn 'ftpClient.rename (từ, đến);' tôi có thể đổi tên nó nhưng vẫn nằm trong cùng một thư mục mà tôi không mong đợi (thư mục sao lưu). Tôi có thể giải quyết nó bằng cách nào? Làm thế nào tôi có thể nhận được đường dẫn sao lưu? những gì là đúng con đường cho đối số thứ hai nếu tôi muốn tập tin được sao chép vào thư mục buckup? Tôi có thư mục gốc mà tất cả các tập tin nằm ở đó và thư mục sao lưu mà tôi tạo nó dưới thư mục gốc. – itro

+0

giống như 'ftpClient.rename ("/root/your_file.txt "," /root/backup/your_file_bak.txt ");'. Một điều cần lưu ý ở đây là nó di chuyển từ thư mục 'from' sang' to'. Bạn sẽ không còn trong thư mục 'from' nữa. –

+0

ohhhhhhhhh không có tôi muốn chỉ có một bản sao của nó không di chuyển nó để sao lưu. – itro

1

Hãy thử cách này,

Tôi đang sử dụng thư viện của apache.

ftpClient.rename (từ đến) sẽ làm cho nó dễ dàng hơn, tôi đã đề cập trong đoạn code dưới đây nơi để thêm ftpClient.rename (từ đến).

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

// $$$$$$$$$$$$$$$$$$$$$$$$$$$$$ Thêm bản sao lưu tại đây $$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$ //

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

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

// $$$$$$$$$$$$$$$ $$$$$$$$$$$$$$ Thêm sao lưu Ở đây $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ //

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

    } 
+0

Tôi nên kiểm tra nếu tập tin tồn tại trong máy chủ sau đó thực hiện sao lưu sau đó tải lên các tập tin. tôi nghĩ rằng bạn đã làm gì đó ở đây – itro

+0

Hãy nhìn vào nó một lần nữa, nếu (kết quả) là khối sẽ thực thi sau khi tập tin được lưu trữ thành công trên máy chủ ..... –

-1

Để sao lưu tại cùng một server (move), bạn có thể sử dụng:

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

Điều này không sao lưu/sao chép một tập tin, nó di chuyển một tập tin. Đó không phải là câu hỏi này là gì. –

Các vấn đề liên quan