從ftp上傳下載檔案(二)

flzhang發表於2016-05-16

ftp工具類,供文章(一)中類呼叫

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 java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FtpKit {
 
 public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) { 
     boolean success = false; 
     FTPClient ftp = new FTPClient(); 
     try { 
         int reply; 
         ftp.setConnectTimeout(2000);
         ftp.connect(url, port);//連線FTP伺服器  
         //如果採用預設埠,可以使用ftp.connect(url)的方式直接連線FTP伺服器  
         ftp.login(username, password);//登入 
         ftp.setBufferSize(1024);
         ftp.setControlEncoding("UTF-8");
         ftp.setFileType(FTP.BINARY_FILE_TYPE);
         ftp.enterLocalActiveMode();
         ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
         reply = ftp.getReplyCode(); 
         if (!FTPReply.isPositiveCompletion(reply)) { 
             ftp.disconnect(); 
             return success; 
         } 
         ftp.changeWorkingDirectory(path); 
         success=ftp.storeFile(filename, input);          
         ftp.logout(); 
     } catch (IOException e) { 
         e.printStackTrace(); 
     } finally { 
         if (ftp.isConnected()) { 
             try { 
                 ftp.disconnect(); 
             } catch (IOException ioe) { 
             } 
         }
     } 
     return success; 
 }
 
 private FTPClient ftpClient; 
    public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE
    public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE
     
    /**
     * 利用FtpConfig進行伺服器連線
     * @param ftpConfig 引數配置Bean類
     * @throws SocketException
     * @throws IOException
     */
    public void connectServer(FtpConfig ftpConfig) throws SocketException, 
            IOException { 
        String server = ftpConfig.getServer(); 
        int port = ftpConfig.getPort(); 
        String user = ftpConfig.getUsername(); 
        String password = ftpConfig.getPassword(); 
        String location = ftpConfig.getLocation(); 
        connectServer(server, port, user, password, location); 
    } 
     
    /**
     * 使用詳細資訊進行伺服器連線
     * @param server:伺服器地址名稱
     * @param port:埠號
     * @param user:使用者名稱
     * @param password:使用者密碼
     * @param path:轉移到FTP伺服器目錄
     * @throws SocketException
     * @throws IOException
     */
    public void connectServer(String server, int port, String user, 
            String password, String path) throws SocketException, IOException { 
        ftpClient = new FTPClient(); 
        ftpClient.connect(server, port); 
        System.out.println("Connected to " + server + "."); 
        //連線成功後的回應碼
        System.out.println(ftpClient.getReplyCode()); 
        ftpClient.login(user, password); 
        if (path!=null&&path.length() != 0) { 
            ftpClient.changeWorkingDirectory(path); 
        } 
     ftpClient.setBufferSize(1024);//設定上傳快取大小
     ftpClient.setControlEncoding("UTF-8");//設定編碼
     ftpClient.setFileType(BINARY_FILE_TYPE);//設定檔案型別
    } 
   
    /**
     * 設定傳輸檔案型別:FTP.BINARY_FILE_TYPE | FTP.ASCII_FILE_TYPE 
     * 二進位制檔案或文字檔案
     * @param fileType
     * @throws IOException
     */
    public void setFileType(int fileType) throws IOException { 
        ftpClient.setFileType(fileType); 
    } 
 
    /**
     * 關閉連線
     * @throws IOException
     */
    public void closeServer() throws IOException { 
        if (ftpClient!=null&&ftpClient.isConnected()) { 
         ftpClient.logout();//退出FTP伺服器
            ftpClient.disconnect();//關閉FTP連線
        } 
    }
   
    /**
     * 轉移到FTP伺服器工作目錄
     * @param path
     * @return
     * @throws IOException
     */
    public boolean changeDirectory(String path) throws IOException { 
        return ftpClient.changeWorkingDirectory(path); 
    } 
   
    /**
     * 在伺服器上建立目錄
     * @param pathName
     * @return
     * @throws IOException
     */
    public boolean createDirectory(String pathName) throws IOException { 
        return ftpClient.makeDirectory(pathName); 
    } 
   
    /**
     * 在伺服器上刪除目錄
     * @param path
     * @return
     * @throws IOException
     */
    public boolean removeDirectory(String path) throws IOException { 
        return ftpClient.removeDirectory(path); 
    } 
     
    /**
     * 刪除所有檔案和目錄
     * @param path
     * @param isAll true:刪除所有檔案和目錄
     * @return
     * @throws IOException
     */
    public boolean removeDirectory(String path, boolean isAll) 
            throws IOException { 
         
        if (!isAll) { 
            return removeDirectory(path); 
        } 
 
        FTPFile[] ftpFileArr = ftpClient.listFiles(path); 
        if (ftpFileArr == null || ftpFileArr.length == 0) { 
            return removeDirectory(path); 
        } 
        //  
        for (FTPFile ftpFile : ftpFileArr) { 
            String name = ftpFile.getName(); 
            if (ftpFile.isDirectory()) { 
             System.out.println("* [sD]Delete subPath ["+path + "/" + name+"]");              
                removeDirectory(path + "/" + name, true); 
            } else if (ftpFile.isFile()) { 
             System.out.println("* [sF]Delete file ["+path + "/" + name+"]");                         
                deleteFile(path + "/" + name); 
            } else if (ftpFile.isSymbolicLink()) { 
 
            } else if (ftpFile.isUnknown()) { 
 
            } 
        } 
        return ftpClient.removeDirectory(path); 
    } 
   
    /**
     * 檢查目錄在伺服器上是否存在 true:存在  false:不存在
     * @param path
     * @return
     * @throws IOException
     */
    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; 
    } 
 
    /**
     * 得到檔案列表,listFiles返回包含目錄和檔案,它返回的是一個FTPFile陣列
     * listNames():只包含目錄的字串陣列
     * String[] fileNameArr = ftpClient.listNames(path);
     * @param path:伺服器上的檔案目錄:/DF4
     */
    public List getFileList(String path) throws IOException { 
        FTPFile[] ftpFiles= ftpClient.listFiles(path); 
        //通過FTPFileFilter遍歷只獲得檔案
/*      FTPFile[] ftpFiles2= ftpClient.listFiles(path,new FTPFileFilter() {
   @Override
   public boolean accept(FTPFile ftpFile) {
    return ftpFile.isFile();
   }
  });  */
        List retList = new ArrayList(); 
        if (ftpFiles == null || ftpFiles.length == 0) { 
            return retList; 
        } 
        for (FTPFile ftpFile : ftpFiles) { 
            if (ftpFile.isFile()) { 
                retList.add(ftpFile.getName()); 
            } 
        } 
        return retList; 
    } 
 
    /**
     * 刪除伺服器上的檔案
     * @param pathName
     * @return
     * @throws IOException
     */
    public boolean deleteFile(String pathName) throws IOException { 
        return ftpClient.deleteFile(pathName); 
    } 
 
    /**
     * 上傳檔案到ftp伺服器
     * 在進行上傳和下載檔案的時候,設定檔案的型別最好是:
     * ftpUtil.setFileType(FtpUtil.BINARY_FILE_TYPE)
     * localFilePath:本地檔案路徑和名稱
     * remoteFileName:伺服器檔名稱
     */
    public boolean uploadFile(String localFilePath, String remoteFileName) 
            throws IOException { 
        boolean flag = false; 
        InputStream iStream = null; 
        try { 
            iStream = new FileInputStream(localFilePath); 
            //我們可以使用BufferedInputStream進行封裝
            //BufferedInputStream bis=new BufferedInputStream(iStream);
            //flag = ftpClient.storeFile(remoteFileName, bis);
            flag = ftpClient.storeFile(remoteFileName, iStream); 
        } catch (IOException e) { 
            flag = false; 
            return flag; 
        } finally { 
            if (iStream != null) { 
                iStream.close(); 
            } 
        } 
        return flag; 
    } 
 
    /**
     * 上傳檔案到ftp伺服器,上傳新的檔名稱和原名稱一樣
     * @param fileName:檔名稱
     * @return
     * @throws IOException
     */
    public boolean uploadFile(String fileName) throws IOException { 
        return uploadFile(fileName, fileName); 
    } 
 
    /**
     * 上傳檔案到ftp伺服器
     * @param iStream 輸入流
     * @param newName 新檔名稱
     * @return
     * @throws IOException
     */
    public boolean uploadFile(InputStream iStream, String newName) 
            throws IOException { 
        boolean flag = false; 
        try { 
            flag = ftpClient.storeFile(newName, iStream); 
        } catch (IOException e) { 
            flag = false; 
            return flag; 
        } finally { 
            if (iStream != null) { 
                iStream.close(); 
            } 
        } 
        return flag; 
    } 
 
    /**
     * 從ftp伺服器上下載檔案到本地
     * @param remoteFileName:ftp伺服器上檔名稱
     * @param localFileName:本地檔名稱
     * @return
     * @throws IOException
     */
    public boolean download(String remoteFileName, String localFileName) 
            throws IOException { 
        boolean flag = false; 
        File outfile = new File(localFileName); 
        OutputStream oStream = null; 
        try { 
            oStream = new FileOutputStream(outfile); 
            //我們可以使用BufferedOutputStream進行封裝
          //BufferedOutputStream bos=new BufferedOutputStream(oStream);
          //flag = ftpClient.retrieveFile(remoteFileName, bos);
            flag = ftpClient.retrieveFile(remoteFileName, oStream); 
        } catch (IOException e) { 
            flag = false; 
            return flag; 
        } finally { 
            oStream.close(); 
        } 
        return flag; 
    } 
    /**
     * 從FTP中獲取輸入流進行檔案讀取
     */
    public InputStream download(String remoteFileName) 
            throws IOException { 
        InputStream is = null;
        try {
            is = ftpClient.retrieveFileStream(remoteFileName);
        } catch (IOException e) {
         e.printStackTrace();
        }
        return is; 
    }
     
    /**
     * 從ftp伺服器上下載檔案到本地
     * @param sourceFileName:伺服器資原始檔名稱
     * @return InputStream 輸入流
     * @throws IOException
     */
    public InputStream downFile(String sourceFileName) throws IOException { 
        return ftpClient.retrieveFileStream(sourceFileName); 
    }
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/750077/viewspace-2100603/,如需轉載,請註明出處,否則將追究法律責任。

相關文章