• sftp上传


    /**
    * @(#)SftpUtils.java 2015-11-13
    *
    * Copyright (c) 1995-2015 Wonders Information Co.,Ltd.
    * 1518 Lianhang Rd,Shanghai 201112.P.R.C.
    * All Rights Reserved.
    *
    * This software is the confidential and proprietary information of Wonders Group.
    * (Social Security Department). You shall not disclose such
    * Confidential Information and shall use it only in accordance with
    * the terms of the license agreement you entered into with Wonders Group.
    *
    * Distributable under GNU LGPL license by gnu.org
    */
    package com.wondersgroup.pub.util;

    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.List;
    import java.util.Random;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;

    import javax.servlet.http.HttpServletResponse;


    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;
    import com.wondersgroup.framework.core.web.struts2.action.BaseAjaxAction;
    import com.wondersgroup.framework.mail.util.BASE64Encoder;
    import com.wondersgroup.mycommom.fjxxb.vo.FjxxbVO;

    /**
    * sftp工具类
    * @author chenyibing
    * 2017-2-21
    */
    public final class SftpUtils extends BaseAjaxAction{

    /** ssh会话 */
    private static volatile Session sshSession = null;

    private static String ftpServer;
    private static int ftpPort;
    private static String ftpAccount;
    private static String ftpPassword;
    private static ChannelSftp sftp = null;

    public void setFtpServer(String ftpServer) {
    SftpUtils.ftpServer = ftpServer;
    }

    public void setFtpPort(int ftpPort) {
    SftpUtils.ftpPort = ftpPort;
    }

    public void setFtpAccount(String ftpAccount) {
    SftpUtils.ftpAccount = ftpAccount;
    }

    public void setFtpPassword(String ftpPassword) {
    SftpUtils.ftpPassword = ftpPassword;
    }

    /**
    * 连接sftp服务器
    *
    * @param host
    * 主机
    * @param port
    * 端口
    * @param username
    * 用户名
    * @param password
    * 密码
    * @return ChannelSftp
    */
    public static ChannelSftp connect(String host, int port, String username,
    String password) throws Exception {


    Channel channel = null;

    try {
    JSch jsch = new JSch();

    jsch.getSession(username, host, port);

    sshSession = jsch.getSession(username, host, port);


    sshSession.setPassword(password);

    sshSession.setConfig("StrictHostKeyChecking", "no");

    sshSession.connect();


    channel = sshSession.openChannel("sftp");

    channel.connect();

    sftp = (ChannelSftp) channel;

    } catch (JSchException e) {
    throw new Exception("Connect to '" + host + "' fail:" + e.getMessage(), e);
    } catch (Exception e) {
    throw new Exception("Connect to '" + host + "' fail:" + e.getMessage(), e);
    }

    return sftp;
    }


    /**
    *
    * @param directory 路径
    * @param uploadFile 文件名称
    * @return true上传成功 fasle 上传失败
    * @throws Exception
    */
    public static boolean upload(
    String directory, String uploadFile) throws Exception {

    boolean isOk=false;

    FileInputStream is = null;

    try {
    sftp = connect(ftpServer, ftpPort, ftpAccount, ftpPassword);

    try {
    sftp.cd(directory);
    } catch (SftpException e) {

    sftp.mkdir(directory);
    sftp.cd(directory);

    }

    File file = new File(uploadFile);

    is = new FileInputStream(file);

    sftp.put(is, file.getName());
    is.close();
    isOk=true;


    } catch (FileNotFoundException e) {
    throw new Exception("file '" + uploadFile + "' not found!", e);
    } catch (Exception e) {
    throw new Exception("upload file '" + uploadFile + "' fail:" + e.getMessage(), e);
    } finally {

    disconnectSftp();
    disconnectSession();
    return isOk;
    }
    }


    /**
    *
    * @param directory 路径
    * @param fileName 文件名称
    * @param file 文件
    * @return true上传成功 fasle 上传失败
    * @throws Exception
    */
    public static boolean uploadListFile(String directory, File file,String fileName) {
    boolean isOk=false;
    try {
    sftp = connect(ftpServer, ftpPort, ftpAccount, ftpPassword);

    try {
    sftp.cd(directory);
    } catch (SftpException e) {

    sftp.mkdir(directory);
    sftp.cd(directory);

    }
    FileInputStream is=new FileInputStream(file);
    sftp.put(is, fileName);
    is.close();
    isOk=true;


    }catch (Exception e) {
    e.printStackTrace();
    //throw new Exception("upload file '" + fileName + "' fail:" + e.getMessage(), e);
    } finally {

    disconnectSftp();
    disconnectSession();

    return isOk;
    }
    }

    /**
    *
    * @param directory 路径
    * @param is 文件流
    * @param fileName 文件名称
    * @return true上传成功 fasle 上传失败
    */
    public static boolean uploadInputStream(String directory, InputStream is,String fileName) {
    boolean isOk=false;
    try {
    sftp = connect(ftpServer, ftpPort, ftpAccount, ftpPassword);

    try {
    sftp.cd(directory);
    } catch (SftpException e) {

    sftp.mkdir(directory);
    sftp.cd(directory);

    }
    sftp.put(is, fileName);
    is.close();
    isOk=true;


    }catch (Exception e) {
    e.printStackTrace();
    //throw new Exception("upload file '" + fileName + "' fail:" + e.getMessage(), e);
    } finally {
    disconnectSftp();
    disconnectSession();
    return isOk;
    }
    }

    /**
    * 下载文件
    *
    * @param ip
    * 远程服务器ip
    * @param port
    * 远程服务器sftp端口号
    * @param userName
    * 远程服务器登录名
    * @param password
    * 远程服务器登录密码
    * @param directory
    * 下载目录
    * @param downloadFile
    * 下载的文件名
    * @param saveFile
    * 存在本地的路径
    */
    public static InputStream download(String filePath,String fileName)
    throws Exception {

    String fileDir = filePath + "/" + fileName;
    InputStream inputStream=null;
    try{
    sftp = connect(ftpServer, ftpPort, ftpAccount, ftpPassword);

    inputStream=sftp.get(fileDir);




    return inputStream;

    } catch (FileNotFoundException e) {
    throw new Exception("file '" + fileName + "' not found!", e);
    } finally {
    //System.out.println(111);
    //sftp.disconnect();
    //disconnectSession();

    }

    }

    /**
    * 批量下载竞赛照片
    * @param fileNameList
    * @return
    */
    public static InputStream batchDownload(List<FjxxbVO> list){
    ByteArrayOutputStream bos=new ByteArrayOutputStream();
    try{
    sftp = connect(ftpServer, ftpPort, ftpAccount, ftpPassword);
    ZipOutputStream out = new ZipOutputStream(bos);
    byte[] buf = new byte[4096];
    for (FjxxbVO fjxxbVO : list) {
    InputStream in = null;
    try {

    in=sftp.get(fjxxbVO.getLj()+"/"+fjxxbVO.getSsmc());

    out.putNextEntry(new ZipEntry(fjxxbVO.getOrgname()+"."+fjxxbVO.getWjlx()));

    int len;
    while ((len = in.read(buf)) > 0) {
    out.write(buf, 0, len);
    }
    out.closeEntry();
    in.close();


    } catch (Exception e) {
    e.printStackTrace();
    }

    }

    //inputStream=sftp.get(fileDir);
    out.close();
    bos.close();

    } catch (FileNotFoundException e) {
    } catch (Exception e) {
    e.printStackTrace();
    }

    return new ByteArrayInputStream(bos.toByteArray());

    }




    public static InputStream download(String fileDir) throws Exception {

    InputStream inputStream = null;
    try {
    sftp = connect(ftpServer, ftpPort, ftpAccount, ftpPassword);

    inputStream = sftp.get(fileDir);

    return inputStream;

    } catch (FileNotFoundException e) {
    throw new Exception("file '" + fileDir + "' not found!", e);
    } finally {
    // System.out.println(111);
    // sftp.disconnect();
    // disconnectSession();

    }

    }

    /**
    * 删除文件
    *
    * @param ip
    * 远程服务器ip
    * @param port
    * 远程服务器sftp端口号
    * @param userName
    * 远程服务器登录名
    * @param password
    * 远程服务器登录密码
    * @param directory
    * 要删除文件所在目录
    * @param deleteFile
    * 要删除的文件
    * @param sftp
    */
    public static void delete(String directory, String deleteFile) throws Exception {


    try {
    sftp = connect(ftpServer, ftpPort, ftpAccount, ftpPassword);

    sftp.cd(directory);
    sftp.rm(deleteFile);

    } catch (Exception e) {
    throw new Exception("Delete file '" + deleteFile + "' fail:" + e.getMessage(),
    e);
    } finally {
    disconnectSftp();
    disconnectSession();
    }
    }

    public static void disconnectSftp() {

    if (null != sftp && sftp.isConnected()) {

    sftp.disconnect();
    sftp.exit();

    sftp = null;
    }
    }

    public static void disconnectSession() {

    if (null != sshSession && sshSession.isConnected()) {

    sshSession.disconnect();

    sshSession = null;
    }
    }

    /**
    * 头像转换成base64
    * @param path
    * @return
    */
    public static String photoToBase64(String fileDir){
    try {
    InputStream inputStream = SftpUtils.download(fileDir);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(2048*3);
    for(int len;(len=inputStream.read())!=-1;){
    baos.write(len);
    }
    baos.flush();
    baos.close();
    byte[] data = baos.toByteArray();
    // 对字节数组Base64编码
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(data);
    } catch (Exception e) {
    e.printStackTrace();
    return null;
    }
    }

    public static void main(String[] args){
    String ip = "172.16.3.165";
    String userName = "root";
    String password = "Root@123";
    int port = 22;
    String uploadFile = "D:"+File.separator+"339005000000000008.pdf";
    String directory = "/home/test";
    String downloadFile = "339005000000000008.pdf";
    String saveFile = "D:/test";
    try {
    //download(directory, downloadFile, saveFile);
    //upload(ip, port, userName, password, directory, uploadFile);
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }


    // 生成文件随机名
    public static String getRandomName(String filename) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    String dateStr = dateFormat.format(new Date());
    Random r = new Random();
    Integer integer = new Integer(r.nextInt(10000));
    String s = String.valueOf(integer);

    filename = dateStr + s + "." + getPostfix(filename);

    return filename;

    }

    // 获取文件类型
    public static String getPostfix(String path) {
    if (path == null || "".equals(path.trim())) {
    return "";
    }
    if (path.contains(".")) {
    return path.substring(path.lastIndexOf(".") + 1, path.length());
    }
    return "";
    }

    }

    需要jar jsch-0.1.53.jar

  • 相关阅读:
    centos编辑文件显示行号
    16.1
    [整理]正睿划水记
    [题解]UVA1519 Dictionary Size
    [题解]CF323C Two permutations
    [题解]CF1527D MEX Tree
    P2216 [HAOI2007]理想的正方形
    CF858D Polycarp's phone book
    ABC214F substrings
    每天一点小知识-20210810
  • 原文地址:https://www.cnblogs.com/wanghongwei123/p/7154232.html
Copyright © 2020-2023  润新知