Ftp相关


package com.logistics.function;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * @author gary
 *
 */
/**
 * @author gary
 * 
 */
public class FtpUtil {
    private FTPClient ftp;

    public FtpUtil() {
        ftp = new FTPClient();
    }

    /**
     * 连接到FTP
     * 
     * @param host
     *            FTP服务器的IP地址
     * @param port
     *            FTP服务器的端口
     * @param userName
     *            FTP服务器的用户名
     * @param passWord
     *            FTP服务器的密码
     */
    public boolean connect(String host, int port, String userName,
            String passWord) {
        boolean result = true;
        try {
            doEvent(RESULT_DOING, "正在连接服务器...");
            ftp.connect(host, port);// 连接FTP服务器
            doEvent(RESULT_DOING, "正在登陆服务器...");
            ftp.login(userName, passWord);// 登陆FTP服务器
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                result = false;
                doEvent(RESULT_ERROR, "未连接到FTP,用户名或密码错误。");
                ftp.disconnect();
            } else {
                doEvent(RESULT_DOING, "FTP连接成功。");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            doEvent(RESULT_ERROR, "FTP的IP地址可能错误,请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            doEvent(RESULT_ERROR, "FTP的端口错误,请正确配置。");
        }
        return result;
    }

    // 断开连接
    public void disconnect() {
        if (ftp.isConnected()) {
            try {
                doEvent(RESULT_DOING, "断开了FTP连接。");
                ftp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void upLoadFileInThread(final String local, final String remote) {
        new Thread() {
            public void run() {
                uploadfile(local, remote);
            };
        }.start();
    }

    /**
     * @param local
     *            本地 如果是文件夹,必须以/结尾
     * @param remote
     *            远程目前只考虑远程为文件夹,不改文件名,必须以/结尾
     */
    public void uploadfile(String local, String remote) {
        File f = new File(local);
        try {
            CreateDirecroty(remote);
        } catch (IOException e1) {
            doEvent(RESULT_ERROR, "创建文件夹出错" + remote);
            e1.printStackTrace();
        }
        if (f.exists()) {
            if (f.isFile()) {
                try {
                    uploadFile(local, remote, f.getName());
                    doEvent(RESULT_OVER, "上传文件结束");
                } catch (IOException e) {
                    e.printStackTrace();
                    doEvent(RESULT_ERROR, "上传文件出错" + f.getName());
                }
            } else if (f.isDirectory() && !f.getName().equals(".")
                    && !f.getName().equals("..")) {
                try {
                    uploadDir(local, remote, f.getName());
                    doEvent(RESULT_OVER, "上传文件结束");
                } catch (IOException e) {
                    e.printStackTrace();
                    doEvent(RESULT_ERROR, "上传文件夹出错" + f.getName());
                }
            }
        } else {
            doEvent(RESULT_ERROR, "没有发现文件" + local);
        }
        disconnect();
    }

    private void createFtpDir(String remoteDir,String remoteNew) throws IOException {
        ftp.changeWorkingDirectory(new String(remoteDir));
        if (!ftp.changeWorkingDirectory(new String(remoteNew))) {
            ftp.makeDirectory(remoteNew);
        }
        ftp.changeWorkingDirectory(remoteNew);
    }

    private void uploadDir(String local, String remote, String dirName)
            throws IOException {
        File file = new File(local);
        if (file.exists()) {
            String remoteDir = remote + dirName + "/";
            createFtpDir(remote,dirName);
            File[] files = file.listFiles();
            for (File f : files) {
                if (f.isDirectory() && !f.getName().equals(".")
                        && !f.getName().equals("..")) {
                    uploadDir(f.getPath(), remoteDir, f.getName());
                } else if (f.isFile()) {
                    uploadFile(f.getPath(), remoteDir, f.getName());
                }
            }
        }
    }

    /**
     * @param local
     * @param remote
     * @param fileName
     * @throws IOException
     */
    private void uploadFile(String local, String remote, String fileName)
            throws IOException {
        //createFtpDir(remote);
        upload(local, fileName);
    }

    /**
     * 上传文件到FTP服务器
     * 
     * @param local
     *            本地文件名称,绝对路径 * @param remote 远程文件路径,支持多级目录嵌套,支持递归创建不存在的目录结构
     * @throws IOException
     */
    private boolean upload(String local, String remote) throws IOException {
        boolean result = true;
        // 设置PassiveMode传输
        ftp.enterLocalPassiveMode();
        // 设置以二进制流的方式传输
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        File f = new File(local);
        uploadFile(remote, f);
        return result;
    }

    private void uploadFile(String remoteFile, File localFile)
            throws IOException {
        InputStream in = new FileInputStream(localFile);
        ftp.storeFile(remoteFile, in);
        in.close();
    }

    public static final int RESULT_ERROR = 0;
    public static final int RESULT_DOING = 1;
    public static final int RESULT_OVER = 2;

    private void doEvent(int result, String strRes) {
        Log.d("gary", result + " " + strRes);
        Message msg = new Message();
        msg.what = result;
        msg.obj = strRes;
        handler.sendMessage(msg);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int r = msg.what;
            String s = (String) msg.obj;
            if (mEvent != null)
                mEvent.onResult(r, s);
            super.handleMessage(msg);
        }
    };
    private IFtpEvent mEvent;

    public void setEvent(IFtpEvent event) {
        mEvent = event;
    }

    public interface IFtpEvent {
        public void onResult(int result, String strRes);
    }

    /** */
    /**
     * 递归创建远程服务器目录
     * 
     * @param remote
     *            远程服务器文件绝对路径
     * 
     * @return 目录创建是否成功
     * @throws IOException
     */
    public boolean CreateDirecroty(String remote) throws IOException {
        boolean success = true;
        String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
        // 如果远程目录不存在,则递归创建远程服务器目录
        if (!directory.equalsIgnoreCase("/")
                && !ftp.changeWorkingDirectory(new String(directory))) {
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            while (true) {
                String subDirectory = new String(remote.substring(start, end));
                if (!ftp.changeWorkingDirectory(subDirectory)) {
                    if (ftp.makeDirectory(subDirectory)) {
                        ftp.changeWorkingDirectory(subDirectory);
                    } else {
                        System.out.println("创建目录失败");
                        success = false;
                        return success;
                    }
                }
                start = end + 1;
                end = directory.indexOf("/", start);
                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        }
        return success;
    }

}

 

 
posted @ 2012-04-26 09:05  meieiem  阅读(1890)  评论(0编辑  收藏  举报