android下使用FTP上传文件、下载文件、新建目录、删除文件工具类


package com.hisign.util;

import android.text.TextUtils;
import android.util.Log;

import com.hisign.qrcebpro.app.Constant;
import com.hisign.qrcebpro.app.MyApplication;
import com.hisign.qrcebpro.utils.LogUtil;
import com.hisign.qrcebpro.utils.PreferenceUtil;
import com.hisign.util.ZipUtils.IResultListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;

/**
 * hongzhen yu create at 2017/7/28
 */

public class FTPManager {
    private static FTPManager instance;
    private FTPManager() {

    }

    /**
     * @return
     * @throws
     * @Title: getInstance
     * @Description: 单例方式提供对象
     */
    public static FTPManager getInstance() {
        if (instance == null) {
            synchronized (FTPManager.class) {
                if (instance == null) {
                    instance = new FTPManager();
                }
            }
        }
        return instance;
    }

    public void ftp4jUpload(final String path, final IResultListener listener) {
        new Thread() {
            public void run() {
                try {
                    String targetName = ftp4jUpload(path);
                    if (listener != null) {
                        listener.onSuccess(targetName);
                    }
                } catch (IllegalStateException | IOException
                        | FTPIllegalReplyException | FTPException
                        | FTPDataTransferException | FTPAbortedException e) {
                    e.printStackTrace();
                    Log.d("lixm", "ftp4jUpload error : ", e);
                    if (listener != null) {
                        listener.onFilure(e.getMessage());
                    }
                }

            }
        }.start();
    }

    /**
     * FTP协议文件上传
     *
     * @param path
     * @throws FTPException
     * @throws FTPIllegalReplyException
     * @throws IOException
     * @throws IllegalStateException
     * @throws FTPAbortedException
     * @throws FTPDataTransferException
     */
    public String ftp4jUpload(String path) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException {
        // 创建客户端
        final FTPClient client = new FTPClient();
        // 不指定端口,则使用默认端口21
        String ip = PreferenceUtil.getNetworkIP(MyApplication.getMyApplication().getApplicationContext());
        String rightIP = "192.168.128.52";
        if (!TextUtils.isEmpty(ip)) {
            String[] ipArr = ip.split("\\.");
            if (ipArr != null && ipArr.length == 4) {
                rightIP = ip;
            }
        }
        int rightPort = 21;
        String port = PreferenceUtil.getNetworkPort(MyApplication.getMyApplication().getApplicationContext());
        if (!TextUtils.isEmpty(port)) {
            rightPort = Integer.valueOf(rightPort);
        }
        client.connect(rightIP, rightPort);
        // 用户登录
        String user = PreferenceUtil.getNetworkUser(MyApplication.getMyApplication().getApplicationContext());
        String rightUser = "test";
        if (!TextUtils.isEmpty(user)) {
            rightUser = user;
        }
        String pwd = PreferenceUtil.getNetworkPwd(MyApplication.getMyApplication().getApplicationContext());
        String rightPwd = "test";
        if (!TextUtils.isEmpty(pwd)) {
            rightPwd = pwd;
        }
        client.login(rightUser, rightPwd);
        String rightFilePath = "";
        String filePath = PreferenceUtil.getNetworkFtpPath(MyApplication.getMyApplication().getApplicationContext());
        if (!TextUtils.isEmpty(filePath)) {
            rightFilePath = "/" + filePath + "/";
            client.changeDirectory(rightFilePath+PreferenceUtil.getUserCode(MyApplication.getMyApplication())+"/");
        }
        File file = new File(path);
        client.upload(file);
        client.rename(srcName, targetName);
        return targetName;
    }

    //从ftp服务器下载文件
    public void ftpDownLoad( final FTPDataTransferListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 创建客户端
                final FTPClient client = new FTPClient();
                //不指定IP的话,默认IP
                String ip = PreferenceUtil.getNetworkIP(MyApplication.getMyApplication().getApplicationContext());
                String rightIP = "192.168.128.52";
                if (!TextUtils.isEmpty(ip)) {
                    String[] ipArr = ip.split("\\.");
                    if (ipArr != null && ipArr.length == 4) {
                        rightIP = ip;
                    }
                }
                // 不指定端口,则使用默认端口21
                int rightPort = 21;
                String port = PreferenceUtil.getNetworkPort(MyApplication.getMyApplication().getApplicationContext());
                if (!TextUtils.isEmpty(port)) {
                    rightPort = Integer.valueOf(rightPort);
                }
                try {
                    client.connect(rightIP, rightPort);
                    // 用户登录
                    String user = PreferenceUtil.getNetworkUser(MyApplication.getMyApplication().getApplicationContext());
                    String rightUser = "test";
                    if (!TextUtils.isEmpty(user)) {
                        rightUser = user;
                    }
                    String pwd = PreferenceUtil.getNetworkPwd(MyApplication.getMyApplication().getApplicationContext());
                    String rightPwd = "test";
                    if (!TextUtils.isEmpty(pwd)) {
                        rightPwd = pwd;
                    }
                    client.login(rightUser, rightPwd);
                    String pathFTP = "/" + "ZIP"+"/";
                    String filePath = PreferenceUtil.getNetworkFtpPath(MyApplication.getMyApplication().getApplicationContext());
                    if (!TextUtils.isEmpty(filePath)) {
                        pathFTP = filePath + "/";
                    }
                    client.changeDirectory(pathFTP+PreferenceUtil.getUserCode(MyApplication.getMyApplication())+"/result");
                    String[] strings = client.listNames();
                    for (int i = 0; i < strings.length; i++) {
                        Log.i("listfile", strings[i]);
                        String name = strings[i];
                        Log.i("file", name);
                        File file = new File(Constant.RESUIT_PATH + name);
                        // 输出流
                        OutputStream outputStream = new FileOutputStream(file);
                        client.download(name, outputStream, 0, listener);
                        outputStream.close();
                        client.logout();
                    }
                } catch (Exception e) {
                }
            }
        }).start();
    }

    /**
     * 在ftp服务器上创建指定目录
     * @param
     */
    public void ftpMakeUserDir() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 创建客户端
                final FTPClient client = new FTPClient();
                // 不指定端口,则使用默认端口21
                String rightIP = "192.168.128.52";
                String ip = PreferenceUtil.getNetworkIP(MyApplication.getMyApplication().getApplicationContext());
                if (!TextUtils.isEmpty(ip)) {
                    String[] ipArr = ip.split("\\.");
                    if (ipArr != null && ipArr.length == 4) {
                        rightIP = ip;
                    }
                }
                int rightPort = 21;
                String port = PreferenceUtil.getNetworkPort(MyApplication.getMyApplication().getApplicationContext());
                if (!TextUtils.isEmpty(port)) {
                    rightPort = Integer.valueOf(rightPort);
                }
                try {
                    client.connect(rightIP, rightPort);//连接ftp服务器
                    //配置用户名
                    String user = PreferenceUtil.getNetworkUser(MyApplication.getMyApplication().getApplicationContext());
                    String rightUser = "test";
                    if (!TextUtils.isEmpty(user)) {
                        rightUser = user;
                    }
                    //配置密码
                    String pwd = PreferenceUtil.getNetworkPwd(MyApplication.getMyApplication().getApplicationContext());
                    String rightPwd = "test";
                    if (!TextUtils.isEmpty(pwd)) {
                        rightPwd = pwd;
                    }
                    client.login(rightUser, rightPwd);//登录到ftp
                    //配置ftp服务器根目录
                    String pathFTP = "/" + "ZIP"+"/";
                    String filePath = PreferenceUtil.getNetworkFtpPath(MyApplication.getMyApplication().getApplicationContext());
                    if (!TextUtils.isEmpty(filePath)) {
                        pathFTP = filePath + "/";
                    }
                    client.changeDirectory(pathFTP);
                    //创建用户目录
                    String userCode = PreferenceUtil.getUserCode(MyApplication.getMyApplication());
                    if (!isDirExist(client, userCode)) {
                        client.createDirectory(userCode);
                        LogUtil.logI("创建目录成功");
                    }
                    LogUtil.logI("存在");
                    client.logout();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (FTPIllegalReplyException e) {
                    e.printStackTrace();
                } catch (FTPException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public void ftpMakeResultDir() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 创建客户端
                final FTPClient client = new FTPClient();
                // 不指定端口,则使用默认端口21
                String rightIP = "192.168.128.52";
                String ip = PreferenceUtil.getNetworkIP(MyApplication.getMyApplication().getApplicationContext());
                if (!TextUtils.isEmpty(ip)) {
                    String[] ipArr = ip.split("\\.");
                    if (ipArr != null && ipArr.length == 4) {
                        rightIP = ip;
                    }
                }
                int rightPort = 21;
                String port = PreferenceUtil.getNetworkPort(MyApplication.getMyApplication().getApplicationContext());
                if (!TextUtils.isEmpty(port)) {
                    rightPort = Integer.valueOf(rightPort);
                }
                try {
                    client.connect(rightIP, rightPort);//连接ftp服务器
                    //配置用户名
                    String user = PreferenceUtil.getNetworkUser(MyApplication.getMyApplication().getApplicationContext());
                    String rightUser = "test";
                    if (!TextUtils.isEmpty(user)) {
                        rightUser = user;
                    }
                    //配置密码
                    String pwd = PreferenceUtil.getNetworkPwd(MyApplication.getMyApplication().getApplicationContext());
                    String rightPwd = "test";
                    if (!TextUtils.isEmpty(pwd)) {
                        rightPwd = pwd;
                    }
                    client.login(rightUser, rightPwd);//登录到ftp
                    //配置ftp服务器根目录
                    String pathFTP = "/" + "ZIP"+"/";
                    String filePath = PreferenceUtil.getNetworkFtpPath(MyApplication.getMyApplication().getApplicationContext());
                    if (!TextUtils.isEmpty(filePath)) {
                        pathFTP = filePath + "/";
                    }
                    //创建用户目录
                    String userCode = PreferenceUtil.getUserCode(MyApplication.getMyApplication());
                    String usrPath=pathFTP+userCode+"/";
                    client.changeDirectory(usrPath);
                    //创建用户目录下的result目录
                    if (!isDirExist(client, "result")) {
                        client.createDirectory("result");
                        LogUtil.logI("resultPath创建目录成功");
                    }
                    LogUtil.logI("result存在");
                    client.logout();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (FTPIllegalReplyException e) {
                    e.printStackTrace();
                } catch (FTPException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    /** 判断Ftp目录是否存在 ,没有原生判断目录是否存在的方法*/
    public boolean isDirExist(FTPClient ftpClient, String dir)

    {
        try {
            ftpClient.changeDirectory(dir);
        } catch (FTPException e) {
            return false;
        } catch (IOException e) {
            return false;
        } catch (FTPIllegalReplyException e) {
            return false;
        }
        return true;
    }

    /**
     * 删除ftp服务器指定文件
     * @param dirName
     */
    private void ftpDeleteFile(final String dir, final String dirName) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 创建客户端
                final FTPClient client = new FTPClient();
                // 不指定端口,则使用默认端口21
                String rightIP = "192.168.128.52";
                String ip = PreferenceUtil.getNetworkIP(MyApplication.getMyApplication().getApplicationContext());
                if (!TextUtils.isEmpty(ip)) {
                    String[] ipArr = ip.split("\\.");
                    if (ipArr != null && ipArr.length == 4) {
                        rightIP = ip;
                    }
                }
                int rightPort = 21;
                String port = PreferenceUtil.getNetworkPort(MyApplication.getMyApplication().getApplicationContext());
                if (!TextUtils.isEmpty(port)) {
                    rightPort = Integer.valueOf(rightPort);
                }
                try {
                    client.connect(rightIP, rightPort);
                    //配置用户名
                    String user = PreferenceUtil.getNetworkUser(MyApplication.getMyApplication().getApplicationContext());
                    String rightUser = "test";
                    if (!TextUtils.isEmpty(user)) {
                        rightUser = user;
                    }
                    //配置密码
                    String pwd = PreferenceUtil.getNetworkPwd(MyApplication.getMyApplication().getApplicationContext());
                    String rightPwd = "test";
                    if (!TextUtils.isEmpty(pwd)) {
                        rightPwd = pwd;
                    }
                    client.login(rightUser, rightPwd);//登录到ftp
                    //配置ftp服务器根目录
                    String pathFTP = "/" + "ZIP"+"/";
                    String filePath = PreferenceUtil.getNetworkFtpPath(MyApplication.getMyApplication().getApplicationContext());
                    if (!TextUtils.isEmpty(filePath)) {
                        pathFTP = filePath + "/";
                    }
                    //创建用户目录
                    String userCode = PreferenceUtil.getUserCode(MyApplication.getMyApplication());
                    String resultPath=pathFTP+userCode+"/"+"result/";
                    client.changeDirectory(resultPath);
                    client.deleteFile(dirName);
                    client.logout();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (FTPIllegalReplyException e) {
                    e.printStackTrace();
                } catch (FTPException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}


import android.util.Log;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipUtils {
	private static final String TAG = "lixm";

	private ZipUtils() {
	}
	
	/**
	 * 
	 * @param sourcePath 源文件路径
	 * @param zipPath    目标文件路径
	 * @param listener   接收返回结果
	 */
	public static void createZip(final String sourcePath, final String zipPath,final IResultListener listener) {
		new Thread(){
			public void run(){
				boolean isOk = false;
				String error = null;
				try {
					isOk = createZip(sourcePath,zipPath);
				} catch (Exception e) {
					error = e.getMessage();
				}
				if(listener != null){
					if(isOk){
						listener.onSuccess(zipPath);
					}else{
						listener.onFilure(error);
					}
				}
			}
		}.start();
	}
	/**
	 * 创建ZIP文件
	 * 
	 * @param sourcePath
	 *            文件或文件夹路径
	 * @param zipPath
	 *            生成的zip文件存在路径(包括文件名)
	 */
	public static boolean createZip(String sourcePath, String zipPath) throws Exception{
		Log.d(TAG, "createZip start, time = " + getCurTime());
		boolean isOk = false;
		File file = new File(sourcePath);
		Log.d(TAG, "sourcePath = " + sourcePath);
		Log.d(TAG, "zipPath = " + zipPath);
		boolean fileExists = file.exists();
		if (!fileExists) {
			Log.d(TAG, "file.exists() = " + fileExists);
			Exception e = new Exception(sourcePath + " not exist!");
			throw e;
		}
		FileOutputStream fos = null;
		ZipOutputStream zos = null;
		try {
			fos = new FileOutputStream(zipPath);
			zos = new ZipOutputStream(fos);
			writeZip(new File(sourcePath), "", zos);
			isOk = true;
		} catch (FileNotFoundException e) {
			throw e;
		} finally {
			try {
				if (zos != null) {
					zos.close();
				}
			} catch (IOException e) {
				Log.d(TAG, "创建ZIP文件失败", e);
				isOk = false;
			}
			Log.d(TAG, "createZip end, time = " + getCurTime());
		}
		return isOk;
	}

	private static void writeZip(File file, String parentPath, ZipOutputStream zos) {
		if (file.exists()) {
			// 处理文件夹
			if (file.isDirectory()) {
				// parentPath+=file.getName()+File.separator;
				File[] files = file.listFiles();
				for (File f : files) {
					writeZip(f, "", zos);
				}
			} else {
				FileInputStream fis = null;
				DataInputStream dis = null;
				try {
					fis = new FileInputStream(file);
					dis = new DataInputStream(new BufferedInputStream(fis));
					ZipEntry ze = new ZipEntry(parentPath + file.getName());
					zos.putNextEntry(ze);
					// 添加编码,如果不添加,当文件以中文命名的情况下,会出现乱码
					// ZipOutputStream的包一定是apache的ant.jar包。JDK也提供了打压缩包,但是不能设置编码
					// zos.setEncoding("GBK");
					byte[] content = new byte[1024];
					int len;
					while ((len = fis.read(content)) != -1) {
						zos.write(content, 0, len);
						zos.flush();
					}
				} catch (FileNotFoundException e) {
					Log.d(TAG, "writeZip , 创建ZIP文件失败", e);
				} catch (IOException e) {
					Log.d(TAG, "writeZip , 创建ZIP文件失败_i0", e);
				} finally {
					try {
						if (dis != null) {
							dis.close();
						}
					} catch (IOException e) {
						Log.d(TAG, "final , 创建ZIP文件失败_i0", e);
					}
				}
			}
		}
	}

	/**
	 * 解压zip文件
	 * 
	 * @param zipPath
	 *            zip文件
	 * @param dstPath
	 *            解压目录
	 * @throws ZipException
	 * @throws IOException
	 */
	public static int upZipFile(String zipPath, String dstPath) throws ZipException, IOException {
		ZipInputStream zis = new ZipInputStream(new FileInputStream(new File(zipPath)));
		ZipEntry zipEntry;
		String subName;
		while ((zipEntry = zis.getNextEntry()) != null) {
			subName = zipEntry.getName();
			// Log.i("info", "subName:"+subName);
			// 如果是个目录
			if (zipEntry.isDirectory()) {
				// 那就得到目录的文件名
				subName = subName.substring(0, subName.length() - 1);
				File folder = new File(dstPath + File.separator + subName);
				folder.mkdirs();
			} else {
				File folder = new File(dstPath);
				if (!folder.exists()) {
					folder.mkdirs();
				}
				File file = new File(dstPath + File.separator + subName);
				FileOutputStream fos = new FileOutputStream(file);
				int len;
				byte[] buf = new byte[1024];
				while ((len = zis.read(buf)) != -1) {
					fos.write(buf, 0, len);
					fos.flush();
				}
				fos.close();
			}
		}
		zis.close();
		return 0;
	}

	/**
	 * 打印当前时间
	 * 
	 * @return
	 */
	public static String getCurTime() {
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss ");
		Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
		String str = formatter.format(curDate);
		return str;
	}
	
	public interface IResultListener{
		public void onSuccess(String zipPath);
		public void onFilure(String errorMsg);
	}
}

 

你可能感兴趣的:(android下使用FTP上传文件、下载文件、新建目录、删除文件工具类)