1. 程式人生 > >ftpClient 的上傳下載及刪除

ftpClient 的上傳下載及刪除

考慮到以後可能用到這些程式碼,還是決定分享出來,方便以後查詢參考。 

1、上傳檔案

        /**
	 * 上傳檔案到ftp.
	 * 
	 * @param inputStream
	 * @param pathString
	 * @param filename
	 * @return
	 */
	public boolean uploadFile(ByteArrayInputStream inputStream, String pathString, String fileName) throws Exception {

		boolean flag = false;
		if (!initConnect()) {
			return false;
		}
		try {
			if (!existDirectory(pathString)) {
				flag = createDirectory(pathString);
			}
			// 變更工作路徑
			flag = ftpClient.changeWorkingDirectory("/" + pathString);
			// 儲存檔案
			flag = ftpClient.storeFile(new String(fileName.getBytes("GBK"), "iso-8859-1"), inputStream);
		} catch (IOException e) {
			e.printStackTrace();
			// 失敗後刪除上傳的檔案
			removeDirectory(pathString, new String(fileName.getBytes("GBK"), "iso-8859-1"));
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (Exception e2) {
				}
			}
		}
		return flag;
	}

2、下載檔案

    /**
     * 從Ftp上下載一個檔案
     * 
     * @param fileName
     * @return InputStream
     * @throws IOException 
     */
    public InputStream downloadFile(String remotePath, String fileName)  {
        InputStream is =null;
        FTPFile[] fs;
        try{
            this.initConnect();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);    <pre name="code" class="java">            // 轉移到FTP伺服器目錄
            ftpClient.changeWorkingDirectory("/"+remotePath);
            //fs = ftpClient.listFiles();
             //檢查遠端檔案是否存在   
            fs = ftpClient.listFiles(new String(fileName.getBytes("GBK"),"iso-8859-1"));
            if(fs.length == 1){   
                is = ftpClient.retrieveFileStream(new String(fileName.getBytes("GBK"),"iso-8859-1"));   
                return is;
            }  
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return is;
    }

3、刪除檔案

     <pre name="code" class="html">            public boolean removeDirectory(String path, String fileName) throws IOException{
			this.initConnect();
			try {
				// 獲取當前Ftp伺服器登入目錄,主要是解決Linux下Ftp伺服器刪除附件問題
				String curDirectory = ftpClient.printWorkingDirectory();
				if (JqLib.isEmpty(curDirectory)) {// 若為空,則定位到根目錄
					curDirectory = "";
				}
				// 刪除檔案
				boolean flag = ftpClient.changeWorkingDirectory(curDirectory + "/" + rootpath + "/" + path);// 轉移到FTP伺服器目錄
				flag = ftpClient.deleteFile(new String(fileName.getBytes("GBK"), "iso-8859-1"));
				if (!flag) {
					throw new UploadNotSuccessException("FTP附件刪除失敗!");
				}

				// 刪除資料夾
				flag = ftpClient.changeWorkingDirectory("/" + rootpath);

				return ftpClient.removeDirectory(path);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				this.closeConnect();
			}
			return true;
		}

4、刪除並備份檔案(這裡的刪除實際是備份檔案,將歷史檔案儲存了下來,放在另外一個資料夾裡面)

      public boolean removeDirectory(String path, String fileName) throws IOException{
		this.initConnect();
		try {
			boolean flag = false;
			String ftpFileName = new String(fileName.getBytes("GBK"), "iso-8859-1");
			// 獲取當前Ftp伺服器登入目錄,主要是解決Linux下Ftp伺服器刪除附件問題
			String curDirectory = ftpClient.printWorkingDirectory();
			if (JqLib.isEmpty(curDirectory)) {// 若為空,則定位到根目錄
				curDirectory = "";
			}

			// 獲得時間戳
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String datePrint = sdf.format(new Date());

			// 拼接目錄
			String pathString = curDirectory + "/" + rootpath + "/" + path;
			String pathStringTrash = curDirectory + "/" + rootpath_trash + "/" + path + "_" + datePrint;

			if (!existDirectory(pathStringTrash) && testPath(pathString)) {
				flag = ftpClient.makeDirectory(pathStringTrash);
			}
			// 原始檔存在時才移動
			if (testPath(pathString)) {
				// 移動檔案
				flag = ftpClient.rename(pathString + "/" + ftpFileName, pathStringTrash + "/" + ftpFileName);
				
				if (!flag) {
					System.out.println("FTP附件移動失敗");
				}
				// 刪除資料夾
				flag = ftpClient.changeWorkingDirectory("/" + rootpath);
			}else{
				System.out.println("原始檔路徑 " + path + "不存在");
			}
			return ftpClient.removeDirectory(path);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			this.closeConnect();
		}
		return true;
	}

5、其他相關方法
  <pre name="code" class="java">       /**
	 * 連線引數初始化
	 */
	public boolean initConnect() {
		try {
			if (ftpClient == null) { // 如果為空,則初始化連線
				if (!isConnectFtp()) {
					return false;
				}
			} else { // 如果不為空,則定位到根目錄
				ftpClient.cwd("/"+rootpath);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 檢查資料夾在當前目錄下是否存在
	 * 
	 * @param path 目錄路徑
	 * @return
	 * @throws IOException boolean
	 */
	public boolean existDirectory(String path) throws IOException {
		boolean flag = false;
		FTPFile[] ftpFileArr = ftpClient.listFiles(path);
		for (FTPFile ftpFile : ftpFileArr) {
			if (ftpFile.isDirectory() && ftpFile.getName().equalsIgnoreCase(path)) {
				flag = true;
				break;
			}
		}
		return flag;
	}  
    
    /**
     * 建立檔案目錄
     * 
     * @param pathName 目錄路徑
     * @return
     * @throws IOException boolean
     */
	public boolean createDirectory(String pathName) throws IOException {
		String[] path = pathName.split("/");
		FTPFile[] file = null;
		for(int j=0;j<path.length;j++) {
			try {
				file = ftpClient.listFiles(path[j]);
				if(file.length==0) {
					throw new Exception();
				}
			}catch(Exception e) {
				//不存在此目錄
				ftpClient.makeDirectory(path[j]);
			}finally {
				ftpClient.changeWorkingDirectory(path[j]);
			}
		}
		return true;
	}

   /**
     * 測試Ftp伺服器是否聯通
     * 
     * @return boolean
     */
    public boolean isConnectFtp() {
        boolean isConnect = true;
        ftpClient = new FTPClient();
        int reply;
        try {
            if (this.port != -1) {
                ftpClient.setDefaultPort(port);
            } else { 
                ftpClient.connect(ip);
            }
            ftpClient.connect(ip);
            ftpClient.login(this.username, this.password);
            reply = ftpClient.getReplyCode();
            ftpClient.setDataTimeout(120000);
               //設定PassiveMode傳輸   
            ftpClient.enterLocalPassiveMode();   
            //設定以二進位制流的方式傳輸   
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);   
            ftpClient.setControlEncoding("UTF-8");   
            
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                isConnect = false;
            }

            return isConnect;
        } catch (SocketException e) {
            isConnect = false;
            e.printStackTrace();
        } catch (IOException e) {
            isConnect = false;
            
        }
        return isConnect;
    }