天天看點

Ftp上傳下載下傳檔案,并能自定義進度條展示(FtpClient)

前一段時間,自己寫了一個java項目釋出在一個免費的java平台上但是該平台給項目的是虛拟路徑并不能上傳檔案。後來想到應用ftp作為上傳檔案的存儲器。

ftp上傳的工具類有sun(sun.net.*)和apache(org.apache.commons.net.ftp.*  這個需要在項目中加載commons-net-1.4.1.jar包)。這次我提供的是基于FtpClient(sun)實作的上傳檔案,因為用FTPClient(apache)想要強行加入上傳檔案的速度檢測比較麻煩,暫時沒有處理以後在整理。

下面說一下我的實作思路:UploadFtp1.java 負責上傳和下載下傳的方法實作,ExStreams.java 重寫其中的方法copy()把檔案讀取的循環中添加上上傳的監聽 ,UploadProgressListener.java 進度的實體類

UploadFtp1.java 

package upload;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;

public class UploadFtp1 
{

	 private sun.net.ftp.FtpClient client=null;
	 private String strServerAddr="";
	 private int iServerPort=0;
	 private String strUserName="";
	 private String strUserPwd="";
 
	 // 監測連接配接是否正常
	 public boolean CheckConn(){
		 boolean bRet=false;
		  try{
		   client.pwd();
		   	bRet=true;
		  }catch(IOException ex){
			  bRet=false;
		  } 
		  return bRet;
	 }
	 
	 //設定資料的傳輸格式為二進制,如果是文本以外的資料如圖檔應該用此方法
	 private  boolean Binary(){
	  boolean bRet=false;
	  try{
		   client.binary();
		   bRet=true;
	  }catch(IOException ex){
		  bRet=false;
	  }
	  	return bRet;
	 }
	 //單位元組字元編碼方案,用于基于文本的資料
	 private  boolean Ascii(){
	  boolean bRet=false;
	  try{
		   client.ascii();
		   bRet=true;
	  }catch(IOException ex){
		  bRet=false;
	  }return bRet;
	 }
	 
 
	 public boolean DisConnect(){
	  boolean bRet=false;
	  try{
	   client.closeServer();
	   bRet=true;
	  }catch(IOException ex){
	   bRet=false;
	  }
	  return bRet;   
	 }

	 /**
	  * 用書上傳本地檔案到ftp伺服器上
	  * @param strSrcFile 上傳檔案的本地路徑
	  * @param strDestFile 上傳到ftp的檔案路徑
	  * @return
	  */
	 public boolean PutFile(String strSrcFile,String strDestFile){
	  boolean bRet=false;	  
	  try{    
		  Binary();
		  TelnetOutputStream   fput=client.put(strDestFile);
		  BufferedOutputStream out = new BufferedOutputStream(fput);
		  File fi = new File(strSrcFile);
		  InputStream srcFile = new FileInputStream(fi);
		  BufferedInputStream in = new BufferedInputStream(srcFile);  
		  UploadProgressListener listener = new UploadProgressListener();
		  ExStreams.copy(in, out,in.available(),true,listener);
		  //一定要關閉檔案流
		  in.close();
	      out.close();
		  System.out.print("put file suc from "+strSrcFile+"   to  "+strDestFile+"\r\n");
	       }
	  catch (IOException ex){   
		   bRet=false;
		   ex.printStackTrace();
	  }  
	  return bRet;
	 }
	 /**
	  * 從ftp上下載下傳所需要的檔案
	  * @param strSrcFile 在ftp上路徑及檔案名
	  * @param strDestFile 要儲存的本地的路徑
	  * @return
	  */
	 public boolean GetFile(String strSrcFile,String strDestFile){
	  boolean bRet=false;	  
	  try{ 
		   Binary();
		   TelnetInputStream fget=client.get(strSrcFile);
		   
		   //為了讀取ftp該檔案的大小,為了計算下載下傳速度和百分比
		   int fileSize = -1;
		   client.sendServer("SIZE "+strSrcFile+"\r\n");
           int res = client.readServerResponse();//z注意:這裡的組合使用是必須得  sendServer 後到 readServerResponse 
           if(res==213){
               String msg= client.getResponseString();
               try{
                   fileSize = Integer.parseInt(msg.substring(3).trim());
               }
               catch(Exception ex){;}
           }
		   BufferedInputStream in = new BufferedInputStream(fget);   
		   File fi = new File(strDestFile);
		   OutputStream srcFile = new FileOutputStream(fi);
		   BufferedOutputStream out = new BufferedOutputStream(srcFile); 	   
		   UploadProgressListener listener = new UploadProgressListener();
		   listener.setFileName(strDestFile);
		   ExStreams.copy(in, out,fileSize, true,listener);
			  //一定要關閉檔案流
		   in.close();
		   out.close();
		   System.out.print("get file suc from "+strSrcFile+"   to  "+strDestFile+"\r\n");
	  }
	  catch (IOException ex){   
		  bRet=false;
		  ex.printStackTrace();
	  }  
	  	  return bRet;
	 }
	 
	 /**
	  * 連接配接ftp伺服器
	  * @param ServerAddr
	  * @param ServerPort
	  * @param UserName
	  * @param UserPwd
	  * @return
	  */
	 public boolean Connect(String ServerAddr,int ServerPort,String UserName,String UserPwd){
		  boolean bRet=false;
		  client=new sun.net.ftp.FtpClient();  
		  this.strServerAddr=ServerAddr;
		  this.iServerPort=ServerPort;
		  this.strUserName=UserName;
		  this.strUserPwd=UserPwd;
  
	  try{  
		   client.openServer(strServerAddr,iServerPort);
		   client.login(strUserName, strUserPwd);
		   System.out.print("connect succeed\n");
		   bRet=true;
	      }
	  catch (IOException ex)
	  {
	   ex.printStackTrace();
	   bRet=false;
	  }
	  
	  return bRet;
	 }
	 /**
	  * ftp連接配接一緻連 直到連接配接成功。
	  * @return
	  */
	 public boolean ConnectTillSuc(){
		 return this.ConnectTillSuc(this.strServerAddr, this.iServerPort, this.strUserName, this.strUserPwd);
	 }
	 // 連接配接,直到成功
	 public boolean ConnectTillSuc(String ServerAddr,int ServerPort,String UserName,String UserPwd){
	  while(!this.Connect(ServerAddr, ServerPort, UserName, UserPwd)){
	   try {
		    System.out.print("connect failed,retry...\n");
		    Thread.sleep(3000);
	   }catch (InterruptedException e) {
		   e.printStackTrace();
	   }
	  }
	  return true;
	 } 
 
 public static void main(String[] args) throws IOException, InterruptedException 
 {  
	 UploadFtp1 client=new UploadFtp1();  
	 boolean b=client.ConnectTillSuc("",21,"","");
	  //client.PutFile("D:\\code.jar", "/test/1344439.jar");
	 client.GetFile("/test/1344469.jar", "D:\\4044-1.jar");
	 client.DisConnect();
  
 }
}
           

ExStreams.java 

package upload;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ExStreams {
	  public static long copy(InputStream pInputStream, OutputStream pOutputStream,long size,boolean pClose,UploadProgressListener uploadListener)
	    throws IOException
	  {
	    return copy(pInputStream, pOutputStream,size, pClose,new byte[8192],uploadListener);
	  }

	  public static long copy(InputStream pIn, OutputStream pOut,long size,boolean pClose,byte[] pBuffer,UploadProgressListener uploadListener)
	    throws IOException
	  {
		  
	    OutputStream out = pOut;
	    InputStream in = pIn;
	    try { long total = 0L;
	      int res;
	      while (true) { res = in.read(pBuffer);
	        if (res == -1) {
	          break;
	        }
	        if (res > 0) {
	          total += res;
	          if (out != null) {
	            out.write(pBuffer, 0, res);
	            System.out.println("檔案的大小"+size+"讀取的大小"+total);
	            uploadListener.update(total, size, 0);
	          }
	        }
	      }
	      if (out != null) {
	        if (pClose)
	          out.close();
	        else {
	          out.flush();
	        }
	        out = null;
	      }
	      in.close();
	      in = null;
	      return total;
	    } finally {
	      if (in != null)
	        try {
	          in.close();
	        }
	        catch (Throwable t)
	        {
	        }
	      if ((pClose) && (out != null))
	        try {
	          out.close();
	        }
	        catch (Throwable t)
	        {
	        }
	    }
	  }
}
           

UploadProgressListener.java

package upload;

import java.io.Serializable;

public class UploadProgressListener implements Serializable{

	/**
	 * 
	 */
	  private static final long serialVersionUID = 1L;
	  private volatile long bytesRead = 0L;
	  private volatile long contentLength = 0L;
	  private String fileName = "";
	 

	

	private long megaBytes = -1L;

	  public void update(long aBytesRead, long aContentLength, int anItem)
	  {
	    this.bytesRead = (aBytesRead / 1024L);
	    this.contentLength = (aContentLength / 1024L);
	    if (this.contentLength == 0L) {
	      this.contentLength = 1L;
	    }
	    long mBytes = aBytesRead / 1048576L;
	    if (this.megaBytes == mBytes) {
	      return;
	    }
	    this.megaBytes = mBytes;
	    System.out.println("上傳或者下載下傳檔案:" + this.fileName + ",檔案的大小:" + aBytesRead + "/" + aContentLength);
	  }

	  public long getBytesRead() {
	    return this.bytesRead;
	  }

	  public long getContentLength() {
	    return this.contentLength;
	  }
	  
	  public String getFileName() {
			return fileName;
		}

	  public void setFileName(String fileName) {
			this.fileName = fileName;
		}

}