Java使用SFTP和FTP兩種連接方式實現對服務器的上傳下載 【我改】


【】如何區分是需要使用SFTP還是FTP?

【】我覺得:

1、看是否已知私鑰

  SFTP 和 FTP 最主要的區別就是 SFTP 有私鑰,也就是在創建連接對象時,SFTP 除了用戶名和密碼外還需要知道私鑰 privateKey  ,如果有 私鑰 那么就用 SFTP,否則 就是用 FTP。

2、看端口號。

  如果端口號是21,那么就用FTP,否則就用 SFTP

===============

轉:

Java使用SFTP和FTP兩種連接方式實現對服務器的上傳下載

版權聲明:本文為原創文章,如有不足之處可以指出,歡迎大家轉載,記得標明出處。 https://blog.csdn.net/a745233700/article/details/79322757

一、Java實現對SFTP服務器的文件的上傳下載

1、添加maven依賴:

  <dependency>
        <groupId>com.jcraft</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.54</version>
    </dependency>


2、SFTPUtil工具類:

   import java.io.ByteArrayInputStream;  
    import java.io.File;  
    import java.io.FileInputStream;  
    import java.io.FileNotFoundException;  
    import java.io.FileOutputStream;  
    import java.io.IOException;  
    import java.io.InputStream;  
    import java.io.UnsupportedEncodingException;  
    import java.util.Properties;  
    import java.util.Vector;  
      
    import org.apache.commons.io.IOUtils;  
    import org.slf4j.Logger;  
    import org.slf4j.LoggerFactory;  
      
    import com.jcraft.jsch.Channel;  
    import com.jcraft.jsch.ChannelSftp;  
    import com.jcraft.jsch.JSch;  
    import com.jcraft.jsch.JSchException;  
    import com.jcraft.jsch.Session;  
    import com.jcraft.jsch.SftpException;
    /**
    * 類說明 sftp工具類
    */
    public class SFTPUtil {
        private transient Logger log = LoggerFactory.getLogger(this.getClass());  
        
        private ChannelSftp sftp;  
            
        private Session session;  
        /** SFTP 登錄用戶名*/    
        private String username;
        /** SFTP 登錄密碼*/    
        private String password;  
        /** 私鑰 */    
        private String privateKey;  
        /** SFTP 服務器地址IP地址*/    
        private String host;  
        /** SFTP 端口*/  
        private int port;  
            
        
        /**  
         * 構造基於密碼認證的sftp對象  
         */    
        public SFTPUtil(String username, String password, String host, int port) {  
            this.username = username;  
            this.password = password;  
            this.host = host;  
            this.port = port;  
        }
        
        /**  
         * 構造基於秘鑰認證的sftp對象
         */  
        public SFTPUtil(String username, String host, int port, String privateKey) {  
            this.username = username;  
            this.host = host;  
            this.port = port;  
            this.privateKey = privateKey;  
        }  
        
        public SFTPUtil(){}  
        
        
        /**
         * 連接sftp服務器
         */  
        public void login(){  
            try {  
                JSch jsch = new JSch();  
                if (privateKey != null) {  
                    jsch.addIdentity(privateKey);// 設置私鑰  
                }  
        
                session = jsch.getSession(username, host, port);  
               
                if (password != null) {  
                    session.setPassword(password);    
                }  
                Properties config = new Properties();  
                config.put("StrictHostKeyChecking", "no");  
                    
                session.setConfig(config);  
                session.connect();  
                  
                Channel channel = session.openChannel("sftp");  
                channel.connect();  
        
                sftp = (ChannelSftp) channel;  
            } catch (JSchException e) {  
                e.printStackTrace();
            }  
        }    
        
        /**
         * 關閉連接 server  
         */  
        public void logout(){  
            if (sftp != null) {  
                if (sftp.isConnected()) {  
                    sftp.disconnect();  
                }  
            }  
            if (session != null) {  
                if (session.isConnected()) {  
                    session.disconnect();  
                }  
            }  
        }  
     
        
        /**  
         * 將輸入流的數據上傳到sftp作為文件。文件完整路徑=basePath+directory
         * @param basePath  服務器的基礎路徑
         * @param directory  上傳到該目錄  
         * @param sftpFileName  sftp端文件名  
         * @param in   輸入流  
         */  
        public void upload(String basePath,String directory, String sftpFileName, InputStream input) throws SftpException{  
            try {   
                sftp.cd(basePath);
                sftp.cd(directory);  
            } catch (SftpException e) {
                //目錄不存在,則創建文件夾
                String [] dirs=directory.split("/");
                String tempPath=basePath;
                for(String dir:dirs){
                    if(null== dir || "".equals(dir)) continue;
                    tempPath+="/"+dir;
                    try{
                        sftp.cd(tempPath);
                    }catch(SftpException ex){
                        sftp.mkdir(tempPath);
                        sftp.cd(tempPath);
                    }
                }
            }  
            sftp.put(input, sftpFileName);  //上傳文件
        }
        
     
        /**
         * 下載文件。
         * @param directory 下載目錄  
         * @param downloadFile 下載的文件
         * @param saveFile 存在本地的路徑
         */    
        public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException{  
            if (directory != null && !"".equals(directory)) {  
                sftp.cd(directory);  
            }  
            File file = new File(saveFile);  
            sftp.get(downloadFile, new FileOutputStream(file));  
        }  
        
        /**  
         * 下載文件
         * @param directory 下載目錄
         * @param downloadFile 下載的文件名
         * @return 字節數組
         */  
        public byte[] download(String directory, String downloadFile) throws SftpException, IOException{  
            if (directory != null && !"".equals(directory)) {  
                sftp.cd(directory);  
            }  
            InputStream is = sftp.get(downloadFile);  
              
            byte[] fileData = IOUtils.toByteArray(is);  
              
            return fileData;  
        }  
        
        
        /**
         * 刪除文件
         * @param directory 要刪除文件所在目錄
         * @param deleteFile 要刪除的文件
         */  
        public void delete(String directory, String deleteFile) throws SftpException{  
            sftp.cd(directory);  
            sftp.rm(deleteFile);  
        }  
        
        
        /**
         * 列出目錄下的文件
         * @param directory 要列出的目錄
         * @param sftp
         */  
        public Vector<?> listFiles(String directory) throws SftpException {  
            return sftp.ls(directory);  
        }  
          
        //上傳文件測試
        public static void main(String[] args) throws SftpException, IOException {  
            SFTPUtil sftp = new SFTPUtil("用戶名", "密碼", "ip地址", 22);  
            sftp.login();  
            File file = new File("D:\\圖片\\t0124dd095ceb042322.jpg");  
            InputStream is = new FileInputStream(file);  
              
            sftp.upload("基礎路徑","文件路徑", "test_sftp.jpg", is);  
            sftp.logout();  
        }  
    }

 



 

二、Java實現對FTP服務器的文件的上傳下載


 

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
     
    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;
     
    /**
     * ftp上傳下載工具類
     */
    public class FtpUtil {
     
        /**
         * Description: 向FTP服務器上傳文件
         * @param host FTP服務器hostname
         * @param port FTP服務器端口
         * @param username FTP登錄賬號
         * @param password FTP登錄密碼
         * @param basePath FTP服務器基礎目錄
         * @param filePath FTP服務器文件存放路徑。文件的路徑為basePath+filePath
         * @param filename 上傳到FTP服務器上的文件名
         * @param input 輸入流
         * @return 成功返回true,否則返回false
         */  
        public static boolean uploadFile(String host, int port, String username, String password, String basePath,
                String filePath, String filename, InputStream input) {
            boolean result = false;
            FTPClient ftp = new FTPClient();
            try {
                int reply;
                ftp.connect(host, port);// 連接FTP服務器
                // 如果采用默認端口,可以使用ftp.connect(host)的方式直接連接FTP服務器
                ftp.login(username, password);// 登錄
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return result;
                }
                //切換到上傳目錄
                if (!ftp.changeWorkingDirectory(basePath+filePath)) {
                    //如果目錄不存在創建目錄
                    String[] dirs = filePath.split("/");
                    String tempPath = basePath;
                    for (String dir : dirs) {
                        if (null == dir || "".equals(dir)) continue;
                        tempPath += "/" + dir;
                        if (!ftp.changeWorkingDirectory(tempPath)) {  //進不去目錄,說明該目錄不存在
                            if (!ftp.makeDirectory(tempPath)) { //創建目錄
                                //如果創建文件目錄失敗,則返回
                                System.out.println("創建文件目錄"+tempPath+"失敗");
                                return result;
                            } else {
                                //目錄存在,則直接進入該目錄
                                ftp.changeWorkingDirectory(tempPath);    
                            }
                        }
                    }
                }
                //設置上傳文件的類型為二進制類型
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                //上傳文件
                if (!ftp.storeFile(filename, input)) {
                    return result;
                }
                input.close();
                ftp.logout();
                result = true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                    }
                }
            }
            return result;
        }
        
        /**
         * Description: 從FTP服務器下載文件
         * @param host FTP服務器hostname
         * @param port FTP服務器端口
         * @param username FTP登錄賬號
         * @param password FTP登錄密碼
         * @param remotePath FTP服務器上的相對路徑
         * @param fileName 要下載的文件名
         * @param localPath 下載后保存到本地的路徑
         * @return
         */  
        public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
                String fileName, String localPath) {
            boolean result = false;
            FTPClient ftp = new FTPClient();
            try {
                int reply;
                ftp.connect(host, port);
                // 如果采用默認端口,可以使用ftp.connect(host)的方式直接連接FTP服務器
                ftp.login(username, password);// 登錄
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return result;
                }
                ftp.changeWorkingDirectory(remotePath);// 轉移到FTP服務器目錄
                FTPFile[] fs = ftp.listFiles();
                for (FTPFile ff : fs) {
                    if (ff.getName().equals(fileName)) {
                        File localFile = new File(localPath + "/" + ff.getName());
     
                        OutputStream is = new FileOutputStream(localFile);
                        ftp.retrieveFile(ff.getName(), is);
                        is.close();
                    }
                }
     
                ftp.logout();
                result = true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                    }
                }
            }
            return result;
        }
     
        //ftp上傳文件測試main函數
        public static void main(String[] args) {
            try {  
                FileInputStream in=new FileInputStream(new File("D:\\Tomcat 5.5\\pictures\\t0176ee418172932841.jpg"));  
                boolean flag = uploadFile("192.168.111.128", 21, "用戶名", "密碼", "/www/images","/2017/11/19", "hello.jpg", in);  
                System.out.println(flag);  
            } catch (FileNotFoundException e) {  
                e.printStackTrace();  
            }  
        }
    }

 
---------------------
作者:a745233700
來源:CSDN
原文:https://blog.csdn.net/a745233700/article/details/79322757
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

 

====================

【】注意:用上面的FTP上傳文件方法,如果上傳的文件名稱為中文,會出現亂碼,解決方法為:

將上傳文件中文件名相關那行

  • //上傳文件
    if (!ftp.storeFile(filename, input)) {
    return result;
    }

     

改為

//上傳文件            

 if (!ftp.storeFile(new String(filename.getBytes("GBK"),"iso-8859-1"), input)) {
        return result;
 }

 

因為FTP上傳時,中文名默認為 iso-8859-1 編碼,而我們在編輯器中寫的中文字符串默認為 GBK 編碼。

 

這是一般情況,如果  領導要求:所有 FTP上傳的文件(文件名)都要用 UTF-8 編碼,那么就需要將上面代碼中的 GBK 改成 UTF-8 ,也就是改成如下

改為

//上傳文件            

 if (!ftp.storeFile(new String(filename.getBytes("utf-8"),"iso-8859-1"), input)) { return result; }

 

還要注意,如果修改了上述的 文件名稱編碼,那么,對應的 從FTP 取文件的 download 方法中的從FTP讀取到的文件名稱也要做對應的轉換,才能得到我們上傳的文件名稱,同樣,我們用 各種 圖形化 工具時也要設置成對應的編碼,才能正確顯示FTP上的文件名。

-------------

FTP針對UTF-8優化版本:

下面是針對 統一約定用 UTF-8 編碼存儲文件的優化版本,上傳、校驗是否存在、下載都沒有問題,可以直接使用:

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

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;
     
    /**
     * ftp上傳下載工具類lb
     */
    public class FtpUtil3 {
     
        /**
         * Description: 向FTP服務器上傳文件
         * @param host FTP服務器hostname
         * @param port FTP服務器端口
         * @param username FTP登錄賬號
         * @param password FTP登錄密碼
         * @param basePath FTP服務器基礎目錄
         * @param filePath FTP服務器文件存放路徑。文件的路徑為basePath+filePath
         * @param filename 上傳到FTP服務器上的文件名
         * @param input 輸入流
         * @return 成功返回true,否則返回false
         */  
        public static boolean uploadFile(String host, int port, String username, String password, String basePath,
                String filePath, String filename, InputStream input) {
            boolean result = false;
            FTPClient ftp = new FTPClient();
            try {
                int reply;
                ftp.connect(host, port);// 連接FTP服務器
                // 如果采用默認端口,可以使用ftp.connect(host)的方式直接連接FTP服務器
                ftp.login(username, password);// 登錄
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return result;
                }
                //切換到上傳目錄
                if (!ftp.changeWorkingDirectory(basePath+filePath)) {
                    //如果目錄不存在創建目錄
                    String[] dirs = filePath.split("/");
                    String tempPath = basePath;
                    for (String dir : dirs) {
                        if (null == dir || "".equals(dir)) continue;
                        tempPath += "/" + dir;
                        if (!ftp.changeWorkingDirectory(tempPath)) {  //進不去目錄,說明該目錄不存在
                            if (!ftp.makeDirectory(tempPath)) { //創建目錄
                                //如果創建文件目錄失敗,則返回
                                System.out.println("創建文件目錄"+tempPath+"失敗");
                                return result;
                            } else {
                                //目錄存在,則直接進入該目錄
                                ftp.changeWorkingDirectory(tempPath);    
                            }
                        }
                    }
                }
                //被動模式(可以提高針對不同FTP服務器的兼容性)
                ftp.enterLocalPassiveMode();
                //設置上傳文件的類型為二進制類型
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                //上傳文件
//                if (!ftp.storeFile(filename, input)) {
                if (!ftp.storeFile(new String(filename.getBytes("UTF-8"), "iso-8859-1"), input)) {
                    return result;
                }
                input.close();
                ftp.logout();
                result = true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                    }
                }
            }
            return result;
        }
        
        /**
         * Description: 從FTP服務器下載文件
         * @param host FTP服務器hostname
         * @param port FTP服務器端口
         * @param username FTP登錄賬號
         * @param password FTP登錄密碼
         * @param remotePath FTP服務器上的相對路徑
         * @param fileName 要下載的文件名
         * @param localPath 下載后保存到本地的路徑
         * @return
         */  
        public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
                String fileName, String localPath) {
            boolean result = false;
            FTPClient ftp = new FTPClient();
            try {
                int reply;
                ftp.connect(host, port);
                // 如果采用默認端口,可以使用ftp.connect(host)的方式直接連接FTP服務器
                ftp.login(username, password);// 登錄
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return result;
                }
                ftp.changeWorkingDirectory(remotePath);// 轉移到FTP服務器目錄
                ftp.setControlEncoding("UTF-8");
                //被動模式(可以提高針對不同FTP服務器的兼容性)
                ftp.enterLocalPassiveMode();
                FTPFile[] fs = ftp.listFiles();
                for (FTPFile ff : fs) {
                    if (ff.getName().equals(fileName)) {
                        File localFile = new File(localPath + "/" + ff.getName());
     
                        OutputStream is = new FileOutputStream(localFile);
                        // ftp需使用ISO-8859-1編碼格式
                        String realName = new String(ff.getName().getBytes("UTF-8"), "ISO-8859-1");
//                        ftp.retrieveFile(ff.getName(), is);
                        ftp.retrieveFile(realName, is);
                        is.close();
                    }
                }
     
                ftp.logout();
                result = true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                    }
                }
            }
            return result;
        }
        
        /**
         * 直接將遠程文件下載到流中【注意:使用完要記住關閉返回的InputStream流】
         * @param host
         * @param port
         * @param username
         * @param password
         * @param remotePath
         * @param fileName
         * @return 直接將遠程文件下載到流中
         */
        public static InputStream downloadFile(String host, int port, String username, String password, String remotePath,
                String fileName) {
            InputStream result = null;
            FTPClient ftp = new FTPClient();
            try {
                int reply;
                ftp.connect(host, port);
                // 如果采用默認端口,可以使用ftp.connect(host)的方式直接連接FTP服務器
                ftp.login(username, password);// 登錄
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return result;
                }
                ftp.changeWorkingDirectory(remotePath);// 轉移到FTP服務器目錄
                ftp.setControlEncoding("UTF-8");
                  //被動模式(可以提高針對不同FTP服務器的兼容性)
                ftp.enterLocalPassiveMode();
                // ftp需使用ISO-8859-1編碼格式
                String realName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                result = ftp.retrieveFileStream(realName);
                ftp.logout();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                    }
                }
            }
            return result;
        }
        
        /**
         * Description: 判斷指定名稱的文件在FTP服務器上是否存在
         * @param host FTP服務器hostname
         * @param port FTP服務器端口
         * @param username FTP登錄賬號
         * @param password FTP登錄密碼
         * @param remotePath FTP服務器上的相對路徑
         * @param fileName 要下載的文件名
         * @param localPath 下載后保存到本地的路徑
         * @return true:存在   false:不存在/或者方法出現錯誤
         * @throws Exception 
         */  
        public static boolean isExistInFTP(String host, int port, String username, String password, String remotePath,
                String fileName){
            boolean result = false;
            FTPClient ftp = new FTPClient();
            try {
                int reply;
                ftp.connect(host, port);
                // 如果采用默認端口,可以使用ftp.connect(host)的方式直接連接FTP服務器
                ftp.login(username, password);// 登錄
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
//                    return result;
                    throw new RuntimeException("FTP連接異常。。。");
                }
                ftp.changeWorkingDirectory(remotePath);// 轉移到FTP服務器目錄
                //這一行一定要有,否則取到的文件名會亂碼,無法和參數 fileName 匹配
                ftp.setControlEncoding("UTF-8");
                  //被動模式(可以提高針對不同FTP服務器的兼容性)
                ftp.enterLocalPassiveMode();
                FTPFile[] fs = ftp.listFiles();
                for (FTPFile ff : fs) {
                    String name = ff.getName();
                    if (name.equals(fileName)) {
                        result = true;
                        break;
//                        OutputStream is = new FileOutputStream(localFile);
//                        ftp.retrieveFile(ff.getName(), is);
//                        is.close();
                    }
                }
                ftp.logout();
            } catch (Exception e) {
                System.out.println("------------查詢FTP上文件是否存在時出現異常,直接返回:不存在------------");
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                    }
                }
            }
            return result;
        }
     
//        ftp上傳文件測試main函數
        public static void main(String[] args) {
            try {  
//                FileInputStream in=new FileInputStream(new File("D:\\Tomcat 5.5\\pictures\\t0176ee418172932841.jpg"));  
//                boolean flag = uploadFile("192.168.111.128", 21, "用戶名", "密碼", "/www/images","/2017/11/19", "hello.jpg", in);  
                
//                FileInputStream in=new FileInputStream(new File("D:/副本2.txt"));

                boolean flag = false;
//                boolean flag = uploadFile("10.18.90.13", 21, "root", "root", "/crm/fileUpload/Account/test","", "副本291195.txt", in); 
//                flag =uploadFile("10.12.9.163",21,"aps","aps","/crm/fileUpload/Account/test","","副本291195.txt",in);
//                String name = "zhicai-beijing-00000385-20190624.txt";
                String name = "記錄.txt";
//                String name = "asgagh2.txt";
//                flag =downloadFile("10.12.9.163", 21, "apps","apps", "/crm/fileUpload/Account/test", name, "D:/a/b/f");
                InputStream input = downloadFile("10.12.9.163", 21, "apps","apps", "/crm/fileUpload/Account/test", name);
                byte[] buffer = new byte[input.available()];
                input.read(buffer);
                FileOutputStream out;
                out = new FileOutputStream("D:/a/b/f/1.txt");
                out.write(buffer);
                out.close();
//                        loadFile("10.12.9.163",21,"apps","apps","/crm/fileUpload/Account/test","","副本291195.txt",in);
//                System.out.println(flag);
//                flag =uploadFile("10.12.4.159",2121,"ji","Y349#","/jitiles/excel","","副本291195.txt",in);
                System.out.println(flag); 
                
//                boolean existInFTP = FtpUtil3.isExistInFTP("10.18.90.13",21,"root","root","/fileUpload/Account/test6","副本291195.txt");
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }
        
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM