jsch/scp实现本地-服务器上传

需求jar包
jsch-0.1.55.jar

package com.topnetwork.util;

import java.io.*;

import com.jcraft.jsch.*;

import java.util.*;


/**
 * ftp上传下载工具类
 */
public class FtpUtil {


    public static void main(String[] args) throws Exception {
        sshSftpUpload("ip", "用户名", "密码", 22, "C:/Users/Administrator/Desktop/exsr.sql", "/ftp/real", "exsr.sql");
        sshSftpDownload("ip", "用户名", "密码", 22, "C:/Users/Administrator/Desktop/xin/exsr.sql", "/ftp/real", "exsr.sql");
    }

    /**
     * 利用JSch包实现SFTP上传文件
     *
     * @param ip   主机IP
     * @param user 主机登陆用户名
     * @param psw  主机登陆密码
     * @param port 主机ssh2登陆端口,如果取默认值,传-1
     *             ChannelSftp类是JSch实现SFTP核心类,它包含了所有SFTP的方法,如:
     *             put():      文件上传
     *             get():      文件下载
     *             cd():       进入指定目录
     *             ls():       得到指定目录下的文件列表
     *             rename():   重命名指定文件或目录
     *             rm():       删除指定文件
     *             mkdir():    创建目录
     *             rmdir():    删除目录
     */
    public static void sshSftpUpload(String ip, String user, String psw, int port, String localDirFileName, String destDir, String fileName) {
        try {
            Session session = null;
            Channel channel = null;
            JSch jsch = new JSch();
            if (port <= 0) {
                //连接服务器,采用默认端口
                session = jsch.getSession(user, ip);
            } else {
                //采用指定的端口连接服务器
                session = jsch.getSession(user, ip, port);
            }

//如果服务器连接不上,则抛出异常
            if (session == null) {
                throw new Exception("session is null");
            }

//设置登陆主机的密码
            session.setPassword(psw);//设置密码
//设置第一次登陆的时候提示,可选值:(ask | yes | no)
            session.setConfig("StrictHostKeyChecking", "no");
//设置登陆超时时间
            session.connect(30000);

            try {
                //创建sftp通信通道
                channel = (Channel) session.openChannel("sftp");
                channel.connect(1000);
                ChannelSftp sftp = (ChannelSftp) channel;

//                sftp.setFilenameEncoding("UTF-8");
//                乱码问题实际上是使用的xftp软件的乱码,使用xshell查看之后并无乱码

//             相当于执行命令 cd /tmp
//             进入服务器指定的文件夹
//             sftp.cd(destDir);
//             进入临时目录文件夹
                sftp.cd("/ftp/temp");
//             以下代码实现从本地上传一个文件到服务器
                String uncode = UUID.randomUUID().toString().replace("-", "").toLowerCase();
                String temp_fileName = uncode + "." + (fileName.split("\\.")[1]);
                OutputStream outstream = sftp.put(temp_fileName);
                InputStream instream = new FileInputStream(new File(localDirFileName));
                byte b[] = new byte[1024];
                int n;
                while ((n = instream.read(b)) != -1) {
                    outstream.write(b, 0, n);
                }
//            传输完成  将文件转移到正式目录
                copyFile(session, "/ftp/temp/" + temp_fileName, "/ftp/real/" + fileName);
//            将临时文件中的数据删除
                sftp.rm(temp_fileName);
                outstream.flush();
                outstream.close();
                instream.close();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                session.disconnect();
                channel.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void copyFile(Session session, String sourceFile, String destinationFile) {
        try {
            ChannelExec channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand("cp " + sourceFile + " " + destinationFile);
            channel.connect();
            while (channel.isConnected()) {
                Thread.sleep(20);
            }
            int status = channel.getExitStatus();
            if (status != 0)
                System.out.println("copy failed, exit status is " + status);
        } catch (Exception e) {
            System.out.println("copy failed");
        }
    }

    /**
     * 利用JSch包实现SFTP下载文件
     *
     * @param ip   主机IP
     * @param user 主机登陆用户名
     * @param psw  主机登陆密码
     * @param port 主机ssh2登陆端口,如果取默认值,传-1
     *             ChannelSftp类是JSch实现SFTP核心类,它包含了所有SFTP的方法,如:
     *             put():      文件上传
     *             get():      文件下载
     *             cd():       进入指定目录
     *             ls():       得到指定目录下的文件列表
     *             rename():   重命名指定文件或目录
     *             rm():       删除指定文件
     *             mkdir():    创建目录
     *             rmdir():    删除目录
     */
    public static void sshSftpDownload(String ip, String user, String psw, int port, String localDirFileName, String destDir, String fileName) {
        try {
            Session session = null;
            Channel channel = null;
            JSch jsch = new JSch();
            if (port <= 0) {
                //连接服务器,采用默认端口
                session = jsch.getSession(user, ip);
            } else {
                //采用指定的端口连接服务器
                session = jsch.getSession(user, ip, port);
            }

//如果服务器连接不上,则抛出异常
            if (session == null) {
                throw new Exception("session is null");
            }

//设置登陆主机的密码
            session.setPassword(psw);//设置密码
//设置第一次登陆的时候提示,可选值:(ask | yes | no)
            session.setConfig("StrictHostKeyChecking", "no");
//设置登陆超时时间
            session.connect(30000);

            try {
                //创建sftp通信通道
                channel = (Channel) session.openChannel("sftp");
                channel.connect(1000);
                ChannelSftp sftp = (ChannelSftp) channel;

//相当于执行命令 cd /tmp
                //进入服务器指定的文件夹
                sftp.cd(destDir);

                //列出服务器指定的文件列表
                Vector v = sftp.ls("*");
                for (int i = 0; i < v.size(); i++) {
                    String detailMsg = v.get(i).toString();
                    String[] allMsg = detailMsg.split(" ");
                    String file = allMsg[allMsg.length - 1];
//                    当文件存在的时候在进行下载操作
                    if (file.equals(fileName)) {
                        InputStream inputStream = sftp.get(fileName);
                        FileOutputStream fileOutputStream = new FileOutputStream(new File(localDirFileName));

                        byte b[] = new byte[1024];
                        int n;
                        while ((n = inputStream.read(b)) != -1) {
                            fileOutputStream.write(b, 0, n);
                        }

                        fileOutputStream.flush();
                        fileOutputStream.close();
                        inputStream.close();
                        sftp.cd(destDir);
                        copyFile(session, destDir + "/" + fileName, "/ftp/history_file/" + fileName);
                        sftp.rm(fileName);
                        break;
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                session.disconnect();
                channel.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 删除文件  用来删除临时文件
     *
     * @param file
     */
    public static void deleteTempFile(File file) {
        file.delete();
    }

}


获取项目的根目录(绝对路径)

File file=new File("");
String abspath=file.getAbsolutePath();

将已有的数据修改成copy语句可执行的文档信息

public static File createCSVFile(ArrayList<Commbo> list, String outPutPath,
                                 String fileName) {
    File csvFile = null;
    BufferedWriter csvFileOutputStream = null;
    try {
        File file = new File(outPutPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        //定义文件名格式并创建
        csvFile = new File(outPutPath + fileName + ".sql");
        file.createNewFile();
        // UTF-8使正确读取分隔符"^"
        //如果生产文件乱码,windows下用gbk,linux用UTF-8
        csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
                csvFile), "UTF-8"), 1024);
        // 写入文件内容
        for (int i = 0; i < list.size(); i++) {
            Commbo commbo = list.get(i);
            StringBuffer sb = new StringBuffer();
            if (StringUtils.isNotEmpty(commbo.getId())) {
                sb.append(commbo.getId() + "^");
            } else {
                sb.append("^");
            }
            if (StringUtils.isNotEmpty(commbo.getText())) {
                sb.append(commbo.getText());
            }
            csvFileOutputStream.write(sb.toString());
            csvFileOutputStream.newLine();
        }
        csvFileOutputStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            csvFileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return csvFile;
}

删除单个文件

deleteFile(abspath+"\\1.sql");
 /**

     * 删除单个文件

     * @param sPath 被删除文件的文件名

     * @return 单个文件删除成功返回true,否则返回false

     */

    public static boolean deleteFile(String sPath) {
        boolean flag = false;

        File file = new File(sPath);

// 路径为文件且不为空则进行删除

        if (file.isFile() && file.exists()) {
            file.delete();

            flag = true;

        }

        return flag;

    }
copy 表(字段1,字段2···) from '/tmp/1.sql' delimiter '^'  null as '';

表到文件,文件到表互相转换
java连接FTP实现上传下载

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值