1. 程式人生 > >java實現ftp上傳、修改、刪除檔案

java實現ftp上傳、修改、刪除檔案

public class FtpUtil {
	
	private static Logger logger = Logger.getLogger(FtpUtil.class);
	private static FTPClient CLIENT = null;
	private static String LOCAL_CHARSET = "GBK";
	private static String SERVER_CHARSET = "ISO-8859-1";
	private static final String FTP_HOST = ConfigureUtil.getString("ftp.host");
	private static final int FTP_PORT = ConfigureUtil.getInt("ftp.post");
	private static final String FTP_USERNAME = ConfigureUtil.getString("ftp.username");
	private static final String FTP_PASSWORD = ConfigureUtil.getString("ftp.password");
	
    /**
     * 獲取FTPClient物件
     *
     * @param ftpHost     FTP主機伺服器
     * @param ftpPassword FTP 登入密碼
     * @param ftpUserName FTP登入使用者名稱
     * @param ftpPort     FTP埠 預設為21
     * @return
     */
    public static void getFTPClient() {
        try {
        	CLIENT = new FTPClient();
        	CLIENT.connect(FTP_HOST, FTP_PORT);// 連線FTP伺服器
        	CLIENT.login(FTP_USERNAME, FTP_PASSWORD);// 登陸FTP伺服器
            if (!FTPReply.isPositiveCompletion(CLIENT.getReplyCode())) {
            	logger.error("未連線到FTP,使用者名稱或密碼錯誤。");
                CLIENT.disconnect();
            } else {
            	logger.info("FTP連線成功。");
            	int reply;
                reply = CLIENT.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                	CLIENT.disconnect();
                }
                
                if (FTPReply.isPositiveCompletion(CLIENT.sendCommand(
    					"OPTS UTF8", "ON"))) {// 開啟伺服器對UTF-8的支援,如果伺服器支援就用UTF-8編碼,否則就使用本地編碼(GBK).
    				LOCAL_CHARSET = "UTF-8";
    			}
                CLIENT.setControlEncoding(LOCAL_CHARSET);
                CLIENT.setFileType(FTP.BINARY_FILE_TYPE);
                CLIENT.enterLocalPassiveMode();
            }
        } catch (SocketException e) {
            e.printStackTrace();
            logger.error("FTP的IP地址可能錯誤,請正確配置。");
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("FTP的埠錯誤,請正確配置。");
        }
    }

    /*
     * 從FTP伺服器下載檔案
     *
     * @param ftpPath FTP伺服器中檔案所在路徑 格式: ftptest/aa
     * @param localPath 下載到本地的位置 格式:H:/download
     * @param fileName 檔名稱
     */
    @SuppressWarnings("static-access")
	public static boolean downloadFtpFile(String ftpPath, String localPath,String fileName) {
        boolean isAppend = false;
    	try {
        	getFTPClient();
            CLIENT.setFileTransferMode(CLIENT.STREAM_TRANSFER_MODE);
            ftpPath = new String(ftpPath.getBytes(LOCAL_CHARSET),SERVER_CHARSET);
            CLIENT.changeWorkingDirectory(ftpPath);
            File localFile = new File(localPath + File.separatorChar + fileName);
            if(!new File(localPath).exists()){
            	new File(localPath).mkdirs();
            }
            if(localFile.exists()){
            	return true;
            }
            OutputStream os = new FileOutputStream(localFile);
            isAppend =  CLIENT.retrieveFile(new String(fileName.getBytes(LOCAL_CHARSET),SERVER_CHARSET), os); 
            os.close();
            CLIENT.logout();
            return isAppend;

        } catch (FileNotFoundException e) {
        	logger.error("沒有找到" + ftpPath + "檔案");
            e.printStackTrace();
        } catch (SocketException e) {
        	logger.error("連線FTP失敗.");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("檔案讀取錯誤。");
            e.printStackTrace();
        }
    	return isAppend;
    }

    /**
     * Description: 向FTP伺服器上傳檔案
     * @param ftpPath  FTP伺服器中檔案所在路徑 格式: ftptest/aa
     * @param fileName ftp檔名稱
     * @param input 檔案流
     * @return 成功返回true,否則返回false
     */
    public static boolean uploadFile(String ftpPath,String fileName,InputStream input) {
        boolean success = false;
        try {
        	getFTPClient();
            ftpPath = new String(ftpPath.getBytes(LOCAL_CHARSET),SERVER_CHARSET);
            CLIENT.makeDirectory(ftpPath);
            CLIENT.changeWorkingDirectory(ftpPath);
            fileName = new String(fileName.getBytes(LOCAL_CHARSET),SERVER_CHARSET);
            success = CLIENT.storeFile(fileName, input);
            logger.info("上傳成功");
            input.close();
            CLIENT.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (CLIENT.isConnected()) {
                try {
                	CLIENT.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }
    
    /**
     * Description: 向FTP伺服器上傳圖片
     * @param ftpPath  FTP伺服器中檔案所在路徑,把路徑按照級別放到陣列中
     * @param fileName ftp檔名稱
     * @param input 檔案流
     * @return 成功返回true,否則返回false
     */
    public static boolean uploadFile(String[] ftpPath,String fileName,InputStream input) {
        boolean success = false;
        try {
        	getFTPClient();
        	String path = "";
        	for(int i=0;i<ftpPath.length;i++){
        		path = new String(ftpPath[i].getBytes(LOCAL_CHARSET),SERVER_CHARSET);
        		if(i == 1){
        			CLIENT.removeDirectory(path);
        		}
                CLIENT.makeDirectory(path);
                CLIENT.changeWorkingDirectory(path);
        	}
        	FTPFile[] files = CLIENT.listFiles();
        	for(FTPFile ff:files){
        		CLIENT.deleteFile(ff.getName());
        	}
            fileName = new String(fileName.getBytes(LOCAL_CHARSET),SERVER_CHARSET);
            success = CLIENT.storeFile(fileName, input);
            logger.info("上傳成功");
            input.close();
            CLIENT.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (CLIENT.isConnected()) {
                try {
                	CLIENT.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }
    
    /**
     * @MethodName  deleteFile
     * @Description 刪除ftp資料夾下面的視訊檔案
     * @param para
     * @return 
     * 
     */
    public static boolean deleteFile(Map<String, Object>para){
    	boolean isAppend = false;
    	try {
    		String path = para.get("path")+"";
    		String name = para.get("name")+"";
    		getFTPClient();
            path = new String(path.getBytes(LOCAL_CHARSET),SERVER_CHARSET);
            CLIENT.changeWorkingDirectory(path);
            name = new String(name.getBytes(LOCAL_CHARSET),SERVER_CHARSET);
            CLIENT.dele(name);
            logger.info("刪除成功");
            CLIENT.logout();
            isAppend = true;
		} catch (Exception e) {
			 e.printStackTrace();
		}finally {
            if (CLIENT.isConnected()) {
                try {
                	CLIENT.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
    	return isAppend;
    }
    
    /**
     * @MethodName  deleteFolder
     * @Description 刪除ftp資料夾
     * @param para
     * @return 
     * 
     */
    public static boolean deleteFolder(String folder){
    	boolean isAppend = false;
    	try {
    		getFTPClient();
    		folder = new String(folder.getBytes(LOCAL_CHARSET),SERVER_CHARSET);
    		isAppend = CLIENT.removeDirectory(folder);
            logger.info("刪除成功");
            CLIENT.logout();
		} catch (Exception e) {
			 e.printStackTrace();
		}finally {
            if (CLIENT.isConnected()) {
                try {
                	CLIENT.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
    	return isAppend;
    }
    
    /**
     * @MethodName  reName
     * @Description 修改檔名稱
     * @param para
     * @return 
     * 
     */
    public static boolean reName(Map<String, Object>para){
    	boolean isAppend = false;
    	try {
    		String path = para.get("path")+"";
    		String name = para.get("name")+"";
    		getFTPClient();
            path = new String(path.getBytes(LOCAL_CHARSET),SERVER_CHARSET);
            name = new String(name.getBytes(LOCAL_CHARSET),SERVER_CHARSET);
            isAppend = CLIENT.rename(path, name);
            logger.info("修改資料夾共成功");
            CLIENT.logout();
		} catch (Exception e) {
			 e.printStackTrace();
		}finally {
            if (CLIENT.isConnected()) {
                try {
                	CLIENT.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
    	return isAppend;
    }

}