如何从ftp服务器获取文件路径?

时间:2014-01-25 07:38:57

标签: java android android-listview ftp-client

此代码获取文件名,但我想获取文件路径:

 private List <String> checkFiles(FTPClient clients){
    List <String> it = new ArrayList <String>();
    try {  

        FTPFile[] ftpFiles = clients.listFiles();  
        int length = ftpFiles.length;  
        for (int i = 0; i < length; i++) {  
          String name = ftpFiles[i].getName();  
          Calendar date = ftpFiles[i].getTimestamp();
          Log.v("aasd", name );
          it.add (name);

        }  
      } catch(Exception e) {  
        e.printStackTrace();  
      }
    return it ;      
  }

2 个答案:

答案 0 :(得分:1)

路径在客户端,而不是文件。

String path = clients.printWorkingDirectory()

答案 1 :(得分:0)

下面的代码发现ftp服务器上任何文件夹中的所有文件路径。 ftpPath就像“ftpserver / folder”。列表包含文件夹中所有文件的路径。

public List<string> GetFilesPath(string ftpPath)
        {
        FtpWebRequest request;
        string FtpServerPath = ftpPath;
        List<string> filePathList=new List<string>();

        try
        {
            request = WebRequest.Create(new Uri(FtpServerPath)) as FtpWebRequest;
            request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;            
            request.UseBinary = true;
            request.UsePassive = true;
            request.KeepAlive = true;
            request.Credentials = new NetworkCredential("ftpuser", "ftpPassword");
            request.ConnectionGroupName = "group";
            Stream rs = (Stream)request.GetResponse().GetResponseStream();

            StreamReader sr = new StreamReader(rs);
            string strList = sr.ReadToEnd();
            string[] lines = null;

            if (strList.Contains("\r\n"))
            {
                lines = strList.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            }
            else if (strList.Contains("\n"))
            {
                lines = strList.Split(new string[] { "\n" }, StringSplitOptions.None);
            }

            if (lines == null || lines.Length == 0)
               return null;
            else{

                foreach (string line in lines)
                {
                    if (line.Length == 0)
                        continue;

                    int x=line.LastIndexOf(' ');
                    int len = line.Length;
                    var str = line.Substring( (x+1), (len - x - 1));
                    var filePath = FtpServerPath+"/"+str;
                    filePathList.Add(filePath);
                }

        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
        }
    }