2012-07-07 50 views
1

下面的代碼上傳文件的FTP服務器上傳空白文件時,FTP路徑有多於一個子目錄

public class UploadFile { 
    static ResourceBundle rsBundle = ResourceBundle.getBundle("com.mindcraft.resources.resources"); 
    public void upload(String host,String username,String pwd,String inputfile,String uploadpath,String zip_filename) 
    {  
     //String zip_file_name= rsBundle.getString("zip_filename"); 
     FTPClient ftp=new FTPClient(); 
     try {   
      int reply; 
      ftp.connect(host); 
      ftp.login(username, pwd); 
      reply = ftp.getReplyCode(); 
      System.out.println("reply1" + reply); 
      if(!FTPReply.isPositiveCompletion(reply)) 
      {    
       ftp.disconnect();   

      }   
      System.out.println("FTP server connected."); 
      ftp.setFileType(FTP.BINARY_FILE_TYPE); 
      InputStream input= new FileInputStream(inputfile); 

      System.out.println("Directory.." + ftp.printWorkingDirectory()); 

      String dirTree=uploadpath; 
      boolean dirExists = true; 
      String[] directories = dirTree.split("/"); 
      for (String dir : directories) 
      { 
       if (!dir.isEmpty()) 
       { 
        if (dirExists) 
        { 
         dirExists = ftp.changeWorkingDirectory(dir); 
         ftp.storeFile(dirTree+zip_filename,input); 
         System.out.println("1.."); 
        } 
        if (!dirExists) 
        { 

         System.out.println("dir tree" + ftp.printWorkingDirectory()); 


         if (!ftp.makeDirectory(dir)) 
         { 

          throw new IOException("Unable to create remote directory '" + dir + "'. error='" + ftp.getReplyString()+"'"); 
          } 
         if (!ftp.changeWorkingDirectory(dir)) 
         { 

          throw new IOException("Unable to change into newly created remote directory '" + dir + "'. error='" + ftp.getReplyString()+"'"); 
         } 
         System.out.println("dir tree" + ftp.printWorkingDirectory()); 
         ftp.storeFile(dirTree+zip_filename,input); 
        } 

        } 
       }  

      System.out.println(ftp.getReplyString()); 
      input.close(); 
      ftp.logout();   
      } 
     catch(Exception e) 
      {      
      System.out.println("err"+ e);   
      e.printStackTrace();  
      } 
     finally 
     { 
      if(ftp.isConnected()) 
      { 
       try 
       { 
        ftp.disconnect(); 

       } 
       catch(Exception ioe) 
       { 

       } 

      } 

     } 
     } 
} 

在它工作正常時,上傳路徑有一個文件夾,例如。 /folder1/

但是,如果存在子文件夾或多個目錄,例如,它會上傳空白文件的字節0。 /folder1/folder2/

可能是什麼問題?

回答

1

ftp.storeFile(dirTree+zip_filename,input);應在調用for後創建所有子目錄,然後轉到正確的目錄。

BTW本來可以幫助引入一個函數makeAndGoToDirectory。

1

喬普埃根拿到了一點,我只想補充一點,如果要恢復的文件/目錄,它是寫一個很好的做法:

,而不是

String[] directories = dirTree.split("/");

因爲它會讓你的代碼更加便攜。 FTP服務器並不總是需要留在Unix/Linux上。