Bootstrap
本文主要介绍Java中使用ftp4j实现向FTP Server服务器上传下载文件方法及示例代码。ftp4j是ftp,ftps和ftpes协议的java实现。

1、ftp4j引用Maven配置

通过github伪maven存储库发布,如果要在maven项目中使用ftp4j作为依赖项,只需将以下存储库定义添加到pom.xml即可:

<repositories>
    <repository>
        <id>github-asbachb-releases</id>
https://raw.github.com/asbachb/mvn-repo/master/releases
    </repository>
</repositories>

要将ftp4j添加为依赖项,只需将以下声明添加到pom.xml即可:

<dependency>
<groupId>com.github.asbachb</groupId>
<artifactId>ftp4j</artifactId>
<version>1.7.3</version>
</dependency>

如果想使用ftp4j的最新官方发布包含以下声明:

<dependency>
<groupId>it.sauronsoftware.ftp4j</groupId>
<artifactId>ftp4j</artifactId>
<version>1.7.2</version>
</dependency>

2、使用ftp4j上传文件

import it.sauronsoftware.ftp4j.FTPClient;
import java.io.File;
/**
 * 该类使用FTP4j客户机库将本地机器中的文件上载到远程FTP服务器
 */
public class FTP_FileUpload
{
        public static void main(String[] args)
        {
                /* Check for input data */
                if (args.length != 3)
                {
                        System.err.println("Usage: java FTP_FileUpload " + "<IpAddress> <UserName> <Password>");
                        System.err.println("Example: java FTP_FileUpload 1.2.3.4 other other");
                        System.exit(1);
                }
                // Assignment
                String ipAddress = args[0];
                String userName = args[1];
                String password = args[2];
                System.out.println("Ip Address = " + ipAddress);
                System.out.println("User = " + userName);
                System.out.println("Pass = " + password);
                // FTP程序操作从这里开始
                FTPClient client = null;
                try
                {
                        // 从实用程序类获取FTP连接
                        client = FTPUtility.connect(ipAddress, userName, password);
                        if (client != null)
                        {
                                try
                                {
                                        //定义要上载的具有完整路径的文件
                                        String filePath = "sample.tar";
                                        File fileUpload = new File(filePath);
                                        System.out.println("Uploading the " + filePath + " to Remote Machine");
                                        //上传文件
                                        client.upload(fileUpload);
                                        System.out.println("Successfully Uploaded the " + filePath + " File to Remote Machine");
                                }
                                catch (Exception e)
                                {
                                        System.err.println("ERROR : Error in Transfering File to Remote Machine");
                                        System.exit(3);
                                }
                        }
                }
                catch (Exception e)
                {
                        System.err.println("ERROR : Error in Connecting to Remote Machine");
                        System.exit(1);
                }
                finally
                {
                        if (client != null)
                        {
                                try
                                {
                                        client.disconnect(true);
                                }
                                catch (Exception e)
                                {
                                        System.err.println("ERROR : Error in disconnecting the Remote Machine");
                                }
                        }
                }
                System.exit(0);
        }
}
/**
 * Lädt den Inhalt des InputStreams local nach remote.
 */
private static void storeFile (String remote, InputStream local, FtpConnection con)
		throws IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException
{
	boolean conWasNull = con == null;
	if (conWasNull)
		con = cons.getClient();
	FTPClient client = con.getFtpClient();
	try
	{
		client.upload(remote, local, 0, 0, null);
	}
	finally
	{
		if (conWasNull)
			con.setBusy(false);
	}
	local.close();
}
public void uploadFile(Context context,File fileName) {
    FTPClient client = new FTPClient();
    SharedPreferences userShare = context.getSharedPreferences("AUDIO_SOURCE", 0);
    String USERNAME = userShare.getString("USERNAME", "");
    String PASSWORD = userShare.getString("PASSWORD", "");
    String FTP_HOST = userShare.getString("FTP_HOST", "");
    Log.d("data" ,USERNAME+" "+PASSWORD+" "+FTP_HOST);
    try {
        client.connect(FTP_HOST);
        client.login(USERNAME, PASSWORD);
        client.setType(FTPClient.TYPE_BINARY);
        client.changeDirectory("/");
        client.upload(fileName, new MyTransferListener());
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("upload Error", e.toString());
        //Toast.makeText(context,"client not connected !", Toast.LENGTH_LONG).show();
        try {
            client.disconnect(true);
        } catch (Exception e2) {
            Log.e("upload Error", e.toString());
            //e2.printStackTrace();
        }
    }
}
public void uploadFile(Context context,File fileName) {
    FTPClient client = new FTPClient();
    SharedPreferences userShare = context.getSharedPreferences("AUDIO_SOURCE", 0);
    String USERNAME = userShare.getString("USERNAME", "");
    String PASSWORD = userShare.getString("PASSWORD", "");
    String FTP_HOST = userShare.getString("FTP_HOST", "");
    Log.d("data" ,USERNAME+" "+PASSWORD+" "+FTP_HOST);
    try {
        client.connect(FTP_HOST);
        client.login(USERNAME, PASSWORD);
        client.setType(FTPClient.TYPE_BINARY);
        client.changeDirectory("/");
        client.upload(fileName, new MyTransferListener());
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("upload Error", e.toString());
        //Toast.makeText(context,"client not connected !", Toast.LENGTH_LONG).show();
        try {
            client.disconnect(true);
        } catch (Exception e2) {
            Log.e("upload Error", e.toString());
            //e2.printStackTrace();
        }
    }
}

3、使用ftp4j下载文件

package in.techdive.upload;
import it.sauronsoftware.ftp4j.FTPClient;
import java.io.File;
/**
这个类使用FTP4j库将文件从远程FTP服务器下载到本地机器。同时下载
*文件,它注册FTP监听器,它会得到通知,一旦FTP下载操作的状态
*下载完成/中止。
 */
public class FTP_FileDownload_WithListener
{
        public static void main(String[] args)
        {
                /* Check for input data */
                if (args.length != 3)
                {
                        System.err.println("Usage: java FTP_FileDownload_WithListener " + "<IpAddress> <UserName> <Password>");
                        System.err.println("Example: java FTP_FileDownload_WithListener 1.2.3.4 other other");
                        System.exit(1);
                }
                // Variable assignment
                String ipAddress = args[0];
                String userName = args[1];
                String password = args[2];
                System.out.println("Ip Address = " + ipAddress);
                System.out.println("User = " + userName);
                System.out.println("Pass = " + password);
                //FTP程序操作从这里开始
                FTPClient client = null;
                try
                {
                        // Get the FTP Connection from the Utility class
                        client = FTPUtility.connect(ipAddress, userName, password);
                        if (client != null)
                        {
                                try
                                {
                                        // 定义要下载的具有完整路径的文件
                                        String filePath = "D:/Sample.zip";
                                        File fileDownload = new File(filePath);
                                        System.out.println("Downloading the " + filePath + " to the Local machine");
                                        // 下载文件
                                        client.download("Sample.zip", fileDownload, new MyFTPListener());
                                        System.out.println("Successfully Downloaded the " + filePath + " file from the Remote Machine");
                                }
                                catch (Exception e)
                                {
                                        System.err.println("ERROR : Error in downloading file from Remote Machine");
                                        System.exit(3);
                                }
                        }
                }
                catch (Exception e)
                {
                        System.err.println("ERROR : Error in Connecting to Remote Machine");
                        System.exit(1);
                }
                finally
                {
                        if (client != null)
                        {
                                try
                                {
                                        client.disconnect(true);
                                }
                                catch (Exception e)
                                {
                                        System.err.println("ERROR : Error in disconnecting the Remote Machine");
                                }
                        }
                }
                System.exit(0);
        }
}

官方文档:https://github.com/asbachb/ftp4j