如何在java中提供FTP地址?

我编写了从FTP服务器下载文件的代码。 由于我本地有我的FTP服务器,我想访问“ftp:// localhost / alfresco”。 这是露天的FTP。

我有以下代码

public class FtpTransfer { public static final void main(String[] args) { FTPClient ftp = new FTPClient(); FileOutputStream br = null; try { ftp.connect("ftp://localhost/alfresco"); ftp.login("admin", "admin"); String file = "KPUB//Admin//TMM//Pickup//TMM_TO_ARTESIA_06152010220246.xml"; br = new FileOutputStream("file"); ftp.retrieveFile("/"+file, br); System.out.println("Downloaded..."); } catch(IOException exception) { System.out.println("Error : "+exception); } } } 

发生以下exception。

 Error : java.net.UnknownHostException: ftp://localhost/alfresco 

请告诉我如何提供FTP主机地址?

下面是一个演示与服务器连接,更改当前工作目录,列出目录中的文件以及将文件下载到某个指定目录的示例。

 package test; import java.io.FileOutputStream; import java.io.IOException; import java.net.SocketException; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; public class FtpTransfer { public static final void main(String[] args) throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.connect("ftp.somedomain.com"); // or "localhost" in your case System.out.println("login: "+ftp.login("username", "pass")); ftp.changeWorkingDirectory("folder/subfolder/"); // list the files of the current directory FTPFile[] files = ftp.listFiles(); System.out.println("Listed "+files.length+" files."); for(FTPFile file : files) { System.out.println(file.getName()); } // lets pretend there is a JPEG image in the present folder that we want to copy to the desktop (on a windows machine) ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // don't forget to change to binary mode! or you will have a scrambled image! FileOutputStream br = new FileOutputStream("C:\\Documents and Settings\\casonkl\\Desktop\\my_downloaded_image_new_name.jpg"); ftp.retrieveFile("name_of_image_on_server.jpg", br); ftp.disconnect(); } } 
 FTPClient f = new FTPClient(); f.connect("localhost"); f.login(username, password); FTPFile[] files = listFiles(directory); 

另见

  • 来自JavaWorld的文章
  • 的JavaDoc

尝试从您的url删除协议(“ftp://”)。

请看一下这个例子 。

FTPClient.connect()方法采用服务器的名称 ,而不是URL。 尝试:

 ftp.connect("localhost"); 

此外,您可能需要将alfresco放在其他地方。 如果它是文件路径的一部分,

 String file = "alfresco/KPUB//Admin//TMM//Pickup//TMM_TO_ARTESIA_06152010220246.xml";