java ftp文件上传sftp文件上传

	<dependency>
		<groupId>commons-net</groupId>
		<artifactId>commons-net</artifactId>
		<version>3.6</version>
	</dependency>

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

ftp:

java 复制代码
import org.apache.commons.net.ftp.FTPClient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FtpTest {

    public static void main(String[] args) {
        ftpUploadFile("192.168.1.129", 21, "root", "123456",
                "D:\\test-ftp.txt",
                "/usr/soft");
    }
    /**
     * ftp上传单个文件
     *
     * @param hostname       服务器地址
     * @param port           端口号
     * @param username       用户名
     * @param password       密码
     * @param uploadFilePath 上传文件路径(包括文件名)
     * @param destPath       ftp上传目录
     */
    public static void ftpUploadFile(String hostname, int port, String username, String password, String uploadFilePath, String destPath) {

        System.out.println("准备连接到ftp");
        try {
            FTPClient ftp = new FTPClient();
            //连接
            ftp.connect(hostname, port);
            //登录
            boolean loginS = ftp.login(username, password);
            if (!loginS) {
                System.out.println("ftp登录失败,用户名或密码错误");
                return;
            } else {
                System.out.println("ftp登录成功");
            }
            // 获取本地文件并上传
            String file = uploadFilePath;
            FileInputStream input = new FileInputStream(file);
            ftp.changeWorkingDirectory(destPath);//跳转目录
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);//必须要设置以二进制的方式传输文件
            ftp.enterLocalPassiveMode();//被动模式
            file = new String(file.getBytes("GBK"), "iso-8859-1");

            if (!ftp.storeFile(new File(file).getName(), input)) {
                System.out.println("失败,服务器返回:" + ftp.getReplyString());//获取上传失败的原因
            } else {
                System.out.println("文件:" + new File(file).getName() + " 上传成功");
            }
            input.close();
            ftp.logout();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("ftp连接失败");
        }
    }
    
}

sftp:

java 复制代码
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

import java.io.*;
import java.util.Properties;
import java.util.Vector;

public class SfptTest {
    public static void main(String[] args) {

        uploadFile("D:\\test-ftp.txt",
                "/usr/soft/",
                "root", "123456",
                "192.168.1.130", 22);
    }
    
    /**
     * @param filePath 文件全路径
     * @param ftpPath  上传到目的端目录
     * @param username
     * @param password
     * @param host
     * @param port
     */
    public static void uploadFile(String filePath, String ftpPath, String username, String password, String host, Integer port) {
        FileInputStream input = null;
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            //获取session  账号-ip-端口
            com.jcraft.jsch.Session sshSession = jsch.getSession(username, host, port);
            //添加密码
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            //严格主机密钥检查
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            //开启session连接
            sshSession.connect();
            //获取sftp通道
            sftp = (ChannelSftp) sshSession.openChannel("sftp");
            //开启
            sftp.connect();
            //文件乱码处理
            /*Class<ChannelSftp> c = ChannelSftp.class;
            Field f = c.getDeclaredField("server_version");
            f.setAccessible(true);
            f.set(sftp, 2);
            sftp.setFilenameEncoding("GBK");*/
            //判断目录是否存在
            try {
                Vector ls = sftp.ls(ftpPath); //ls()得到指定目录下的文件列表
                /*if (ls == null) {   //ls不会为null,哪怕它是一个空目录
                    sftp.mkdir(ftpPath);
                }*/
            } catch (SftpException e) {
                sftp.mkdir(ftpPath);
            }
            sftp.cd(ftpPath);
            String filename = filePath.substring(filePath.lastIndexOf(File.separator) + 1); //附件名字
            //filename = new String(filename.getBytes("GBK"), StandardCharsets.ISO_8859_1);
            input = new FileInputStream(new File(filePath));
            sftp.put(input, filename);
            //设定777权限,转为8进制放入chmod中
            //sftp.chmod(Integer.parseInt("777", 8), ftpPath + filename);
            input.close();
            sftp.disconnect();
            sshSession.disconnect();
            System.out.println("================上传成功!==================");
        } catch (Exception e) {
            System.out.println("================上传失败!==================");
            e.printStackTrace();
        }
    }

    /**
     * @param directory    SFTP服务器的文件路径
     * @param downloadFile SFTP服务器上的文件名
     * @param saveFile     保存到本地路径
     * @param username
     * @param password
     * @param host
     * @param port
     */
    public static void downloadFile(String directory, String downloadFile, String saveFile, String username, String password, String host, Integer port) throws JSchException, IOException {
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            //获取session  账号-ip-端口
            com.jcraft.jsch.Session sshSession = jsch.getSession(username, host, port);
            //添加密码
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            //严格主机密钥检查
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            //开启session连接
            sshSession.connect();
            //获取sftp通道
            sftp = (ChannelSftp) sshSession.openChannel("sftp");
            //开启
            sftp.connect();
            if (directory != null && !"".equals(directory)) {
                sftp.cd(directory);
            }
            FileOutputStream output = new FileOutputStream(new File(saveFile));
            sftp.get(downloadFile, output);
            output.close();
            sftp.disconnect();
            sshSession.disconnect();
            System.out.println("================下载成功!==================");
        } catch (SftpException | FileNotFoundException | JSchException e) {
            System.out.println("文件下载异常!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
相关推荐
程序员南飞41 分钟前
ps aux | grep smart_webrtc这条指令代表什么意思
java·linux·ubuntu·webrtc
弥琉撒到我44 分钟前
微服务swagger解析部署使用全流程
java·微服务·架构·swagger
一颗花生米。2 小时前
深入理解JavaScript 的原型继承
java·开发语言·javascript·原型模式
问道飞鱼2 小时前
Java基础-单例模式的实现
java·开发语言·单例模式
学习使我快乐012 小时前
JS进阶 3——深入面向对象、原型
开发语言·前端·javascript
通信仿真实验室3 小时前
(10)MATLAB莱斯(Rician)衰落信道仿真1
开发语言·matlab
勿语&3 小时前
Element-UI Plus 暗黑主题切换及自定义主题色
开发语言·javascript·ui
ok!ko5 小时前
设计模式之原型模式(通俗易懂--代码辅助理解【Java版】)
java·设计模式·原型模式
2402_857589366 小时前
“衣依”服装销售平台:Spring Boot框架的设计与实现
java·spring boot·后端
吾爱星辰6 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin