如何在java中给出FTP地址? [英] How to give FTP address in java?

查看:30
本文介绍了如何在java中给出FTP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了从 FTP 服务器下载文件的代码.因为我在本地有我的 FTP 服务器,我想像ftp://localhost/alfresco"一样访问.这是 alfresco 的 FTP.

I have written the code which downloads the file from FTP server. Since I have my FTP server locally and I want to access like "ftp://localhost/alfresco". It was alfresco's 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);
    }
}
}

出现以下异常.

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

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

Please let me know how should I give the FTP Host Address?

推荐答案

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

Here is an example demonstrating connection to a server, changing present working directory, listing files in a directory and downloading a file to some specified directory.

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

 }
}

这篇关于如何在java中给出FTP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆