溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java連接服務器的兩種方式SFTP和FTP有什么區(qū)別

發(fā)布時間:2023-02-25 10:40:31 來源:億速云 閱讀:135 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹了Java連接服務器的兩種方式SFTP和FTP有什么區(qū)別的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Java連接服務器的兩種方式SFTP和FTP有什么區(qū)別文章都會有所收獲,下面我們一起來看看吧。

區(qū)別

FTP是一種文件傳輸協議,一般是為了方便數據共享的。包括一個FTP服務器和多個FTP客戶端。FTP客戶端通過FTP協議在服務器上下載資源。FTP客戶端通過FTP協議在服務器上下載資源。而一般要使用FTP需要在服務器上安裝FTP服務。

而SFTP協議是在FTP的基礎上對數據進行加密,使得傳輸的數據相對來說更安全,但是傳輸的效率比FTP要低,傳輸速度更慢(不過現實使用當中,沒有發(fā)現多大差別)。SFTP和SSH使用的是相同的22端口,因此免安裝直接可以使用。

總結:

一;FTP要安裝,SFTP不要安裝。

二;SFTP更安全,但更安全帶來副作用就是的效率比FTP要低。

FtpUtil

<!--ftp文件上傳-->
<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.6</version>
</dependency>
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.*;
@Component
public class FtpUtil {
    private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);
    //ftp服務器地址
    @Value("${ftp.server}")
    private String hostname;
    //ftp服務器端口
    @Value("${ftp.port}")
    private int port;
    //ftp登錄賬號
    @Value("${ftp.userName}")
    private String username;
    //ftp登錄密碼
    @Value("${ftp.userPassword}")
    private String password;
    /**
    * 初始化FTP服務器
    *
    * @return
    */
    public FTPClient getFtpClient() {
        FTPClient ftpClient = new FTPClient();
        ftpClient.setControlEncoding("UTF-8");
        try {
            //設置連接超時時間
            ftpClient.setDataTimeout(1000 * 120);
            logger.info("連接FTP服務器中:" + hostname + ":" + port);
            //連接ftp服務器
            ftpClient.connect(hostname, port);
            //登錄ftp服務器
            ftpClient.login(username, password);
            // 是否成功登錄服務器
            int replyCode = ftpClient.getReplyCode();
            if (FTPReply.isPositiveCompletion(replyCode)) {
                logger.info("連接FTP服務器成功:" + hostname + ":" + port);
            } else {
                logger.error("連接FTP服務器失敗:" + hostname + ":" + port);
                closeFtpClient(ftpClient);
            }
        } catch (IOException e) {
            logger.error("連接ftp服務器異常", e);
        }
        return ftpClient;
    }
    /**
     * 上傳文件
     *
     * @param pathName    路徑
     * @param fileName    文件名
     * @param inputStream 輸入文件流
     * @return
     */
    public boolean uploadFileToFtp(String pathName, String fileName, InputStream inputStream) {
        boolean isSuccess = false;
        FTPClient ftpClient = getFtpClient();
        try {
            if (ftpClient.isConnected()) {
                logger.info("開始上傳文件到FTP,文件名稱:" + fileName);
                //設置上傳文件類型為二進制,否則將無法打開文件
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                //路徑切換,如果目錄不存在創(chuàng)建目錄
                if (!ftpClient.changeWorkingDirectory(pathName)) {
                    boolean flag = this.changeAndMakeWorkingDir(ftpClient, pathName);
                    if (!flag) {
                        logger.error("路徑切換(創(chuàng)建目錄)失敗");
                        return false;
                    }
                }
                //設置被動模式,文件傳輸端口設置(如上傳文件夾成功,不能上傳文件,注釋這行,否則報錯refused:connect)
                ftpClient.enterLocalPassiveMode();
                ftpClient.storeFile(fileName, inputStream);
                inputStream.close();
                ftpClient.logout();
                isSuccess = true;
                logger.info(fileName + "文件上傳到FTP成功");
            } else {
                logger.error("FTP連接建立失敗");
            }
        } catch (Exception e) {
            logger.error(fileName + "文件上傳異常", e);
 
        } finally {
            closeFtpClient(ftpClient);
            closeStream(inputStream);
        }
        return isSuccess;
    }
    /**
     * 刪除文件
     *
     * @param pathName 路徑
     * @param fileName 文件名
     * @return
     */
    public boolean deleteFile(String pathName, String fileName) {
        boolean flag = false;
        FTPClient ftpClient = getFtpClient();
        try {
            logger.info("開始刪除文件");
            if (ftpClient.isConnected()) {
                //路徑切換
                ftpClient.changeWorkingDirectory(pathName);
                ftpClient.enterLocalPassiveMode();
                ftpClient.dele(fileName);
                ftpClient.logout();
                flag = true;
                logger.info("刪除文件成功");
            } else {
                logger.info("刪除文件失敗");
            }
        } catch (Exception e) {
            logger.error(fileName + "文件刪除異常", e);
        } finally {
            closeFtpClient(ftpClient);
        }
        return flag;
    }
    /**
     * 關閉FTP連接
     *
     * @param ftpClient
     */
    public void closeFtpClient(FTPClient ftpClient) {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                logger.error("關閉FTP連接異常", e);
            }
        }
    }
    /**
     * 關閉文件流
     *
     * @param closeable
     */
    public void closeStream(Closeable closeable) {
        if (null != closeable) {
            try {
                closeable.close();
            } catch (IOException e) {
                logger.error("關閉文件流異常", e);
            }
        }
    }
    /**
     * 路徑切換(沒有則創(chuàng)建)
     *
     * @param ftpClient FTP服務器
     * @param path      路徑
     */
    public void changeAndMakeWorkingDir(FTPClient ftpClient, String path) {
        boolean flag = false;
        try {
            String[] path_array = path.split("/");
            for (String s : path_array) {
                boolean b = ftpClient.changeWorkingDirectory(s);
                if (!b) {
                    ftpClient.makeDirectory(s);
                    ftpClient.changeWorkingDirectory(s);
                }
            }
            flag = true;
        } catch (IOException e) {
            logger.error("路徑切換異常", e);
        }
        return flag;
    }
    /**
     * 從FTP下載到本地文件夾
     *
     * @param ftpClient      FTP服務器
     * @param pathName       路徑
     * @param targetFileName 文件名
     * @param localPath      本地路徑
     * @return
     */
    public boolean downloadFile(FTPClient ftpClient, String pathName, String targetFileName, String localPath) {
        boolean flag = false;
        OutputStream os = null;
        try {
            System.out.println("開始下載文件");
            //切換FTP目錄
            ftpClient.changeWorkingDirectory(pathName);
            ftpClient.enterLocalPassiveMode();
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile file : ftpFiles) {
                String ftpFileName = file.getName();
                if (targetFileName.equalsIgnoreCase(ftpFileName)) {
                    File localFile = new File(localPath + targetFileName);
                    os = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(file.getName(), os);
                    os.close();
                }
            }
            ftpClient.logout();
            flag = true;
            logger.info("下載文件成功");
        } catch (Exception e) {
            logger.error("下載文件失敗", e);
        } finally {
            closeFtpClient(ftpClient);
            closeStream(os);
        }
        return flag;
    }
}

SFTPUtil

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.54</version>
</dependency>
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;
@Component
public class SFTPUtil {
    private static final Logger logger = LoggerFactory.getLogger(SFTPUtil.class);
    private Session session = null;
    private ChannelSftp channel = null;
    private int timeout = 60000;
    /**
    * 連接sftp服務器
    */
    public boolean connect(String ftpUsername, String ftpAddress, int ftpPort, String ftpPassword) {
        boolean isSuccess = false;
        if (channel != null) {
            System.out.println("通道不為空");
            return false;
        }
        //創(chuàng)建JSch對象
        JSch jSch = new JSch();
        try {
            // 根據用戶名,主機ip和端口獲取一個Session對象
            session = jSch.getSession(ftpUsername, ftpAddress, ftpPort);
            //設置密碼
            session.setPassword(ftpPassword);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            //為Session對象設置properties
            session.setConfig(config);
            //設置超時
            session.setTimeout(timeout);
            //通過Session建立連接
            session.connect();
            System.out.println("Session連接成功");
            // 打開SFTP通道
            channel = (ChannelSftp) session.openChannel("sftp");
            // 建立SFTP通道的連接
            channel.connect();
            System.out.println("通道連接成功");
            isSuccess = true;
        } catch (JSchException e) {
            logger.error("連接服務器異常", e);
        }
        return isSuccess;
    }
    /**
     * 關閉連接
     */
    public void close() {
        //操作完畢后,關閉通道并退出本次會話
        if (channel != null && channel.isConnected()) {
            channel.disconnect();
        }
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
    }
    /**
    * 文件上傳
    * 采用默認的傳輸模式:OVERWRITE
    * @param src      輸入流
    * @param dst      上傳路徑
    * @param fileName 上傳文件名
    *
    * @throws SftpException
    */
    public boolean upLoadFile(InputStream src, String dst, String fileName) throws SftpException {
        boolean isSuccess = false;
        try {
            if(createDir(dst)) {
                channel.put(src, fileName);
                isSuccess = true;
            }
        } catch (SftpException e) {
            logger.error(fileName + "文件上傳異常", e);
        }
        return isSuccess;
    }
    /**
    * 創(chuàng)建一個文件目錄
    *
    * @param createpath  路徑
    * @return
    */
    public boolean createDir(String createpath) {
        boolean isSuccess = false;
        try {
            if (isDirExist(createpath)) {
                channel.cd(createpath);
                return true;
            }
            String pathArry[] = createpath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            for (String path : pathArry) {
                if (path.equals("")) {
                    continue;
                }
                filePath.append(path + "/");
                if (isDirExist(filePath.toString())) {
                    channel.cd(filePath.toString());
                } else {
                    // 建立目錄
                    channel.mkdir(filePath.toString());
                    // 進入并設置為當前目錄
                    channel.cd(filePath.toString());
                }
            }
            channel.cd(createpath);
            isSuccess = true;
        } catch (SftpException e) {
            logger.error("目錄創(chuàng)建異常!", e);
        }
        return isSuccess;
    }
    /**
     * 判斷目錄是否存在
     * @param directory     路徑
     * @return
     */
    public boolean isDirExist(String directory) {
        boolean isSuccess = false;
        try {
            SftpATTRS sftpATTRS = channel.lstat(directory);
            isSuccess = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
            if (e.getMessage().toLowerCase().equals("no such file")) {
                isSuccess = false;
            }
        }
        return isSuccess;
    }
    /**
    * 重命名指定文件或目錄
    *
    */
    public boolean rename(String oldPath, String newPath) {
        boolean isSuccess = false;
        try {
            channel.rename(oldPath, newPath);
            isSuccess = true;
        } catch (SftpException e) {
            logger.error("重命名指定文件或目錄異常", e);
        }
        return isSuccess;
    }
    /**
    * 列出指定目錄下的所有文件和子目錄。
    */
    public Vector ls(String path) {
        try {
            Vector vector = channel.ls(path);
            return vector;
        } catch (SftpException e) {
            logger.error("列出指定目錄下的所有文件和子目錄。", e);
        }
        return null;
    }
    /**
    * 刪除文件
    *
    * @param directory  linux服務器文件地址
    * @param deleteFile 文件名稱
    */
    public boolean deleteFile(String directory, String deleteFile) {
        boolean isSuccess = false;
        try {
            channel.cd(directory);
            channel.rm(deleteFile);
            isSuccess = true;
        } catch (SftpException e) {
            logger.error("刪除文件失敗", e);
        }
        return isSuccess;
    }
    /**
    * 下載文件
    *
    * @param directory    下載目錄
    * @param downloadFile 下載的文件
    * @param saveFile     下載到本地路徑
    */
    public boolean download(String directory, String downloadFile, String saveFile) {
        boolean isSuccess = false;
        try {
            channel.cd(directory);
            File file = new File(saveFile);
            channel.get(downloadFile, new FileOutputStream(file));
            isSuccess = true;
        } catch (SftpException e) {
            logger.error("下載文件失敗", e);
        } catch (FileNotFoundException e) {
            logger.error("下載文件失敗", e);
        }
        return isSuccess;
    }
}

問題

文件超出默認大小

#單文件上傳最大大小,默認1Mb
spring.http.multipart.maxFileSize=100Mb
#多文件上傳時最大大小,默認10Mb
spring.http.multipart.maxRequestSize=500MB

關于“Java連接服務器的兩種方式SFTP和FTP有什么區(qū)別”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“Java連接服務器的兩種方式SFTP和FTP有什么區(qū)別”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI