1. 程式人生 > >android下使用FTP上傳檔案、下載檔案、新建目錄、刪除檔案工具類

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