java 用于文件ftp上传和下载

/**
 * 用于文件ftp上传和下载
 */
public class FtpFileUtil {

    private static final Logger log = LoggerFactory.getLogger(FtpFileUtil.class);


    /**
     * 连接sftp服务器
     * @param host 远程主机ip地址
     * @param port sftp连接端口,null 时为默认端口
     * @param user 用户名
     * @param password 密码
     * @return
     * @throws JSchException
     */
    public static Session connect(String host, Integer port, String user, String password) throws JSchException{
        Session session = null;
        try {
            JSch jsch = new JSch();
            if(port != null){
                session = jsch.getSession(user, host, port.intValue());
            }else{
                session = jsch.getSession(user, host);
            }
            session.setPassword(password);
            //设置第一次登陆的时候提示,可选值:(ask | yes | no)
            session.setConfig("StrictHostKeyChecking", "no");
            //30秒连接超时
            session.connect(30000);
        } catch (JSchException e) {
            e.printStackTrace();
            System.out.println("SFTPUitl 获取连接发生错误");
            throw e;
        }
        return session;
    }


    public static void upload(Session session, InputStream inputStream,String dir) {
        ChannelSftp sftp = null;
        Channel channel = null;
        try {

            channel = session.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            if(null != sftp){
            }
            sftp.put(inputStream,dir);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeChannel(sftp);
            closeChannel(channel);
            closeSession(session);
        }
    }

    public static void upload(String host, int port, String username, final String password, InputStream inputStream,String dir) {
        ChannelSftp sftp = null;
        Channel channel = null;
        Session session = null;
        try {
            JSch jsch = new JSch();
            //是否需要私钥路径
            // jsch.addIdentity("");
            jsch.getSession(username, host, port);
            session = jsch.getSession(username, host, port);
            session.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            session.setConfig(sshConfig);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            if(null != sftp){
                log.info("已连接上"+host+"服务器上---------------------");
            }
            sftp.put(inputStream,dir);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeChannel(sftp);
            closeChannel(channel);
            closeSession(session);
        }
    }


    /*public static ChannelSftp connect(String ip,String userName,String pwd,int port) throws JSchException
    {

        Session sshSession = null;
        JSch jsch = new JSch();
        sshSession = jsch.getSession(userName,ip,port);

        sshSession.setPassword(pwd);
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking","no");
        sshConfig.put("PreferredAuthentications","password,keyboard-interactive");
        sshSession.setConfig(sshConfig);


        sshSession.connect();//可设置超时时间
        //此处开始为端口映射到本地的部分
        sshSession.setPortForwardingL(22,"10.222.2.106",22);
        //完成上诉映射之后,即可通过本地端口连接了
        Session session = jsch.getSession("sftp","127.0.0.1",22);
        Properties remoteCfg = new Properties();
        remoteCfg.put("StrictHostKeyChecking","no");
        remoteCfg.put("PreferredAuthentications","keyboard-interactive");
        session.setConfig(remoteCfg);
        session.setPassword("sftp");
        session.connect();
        //
        Channel channel = (Channel) session.openChannel("sftp");//创建sftp通信通道
        channel.connect();
        ChannelSftp sftp = (ChannelSftp) channel;

        return sftp;
    }*/

    /**
     * src  ftp 上的路径
     * dir  当前路径
     * @param host
     * @param port
     * @param username
     * @param password
     * @param src
     * @param dir
     */
    public static void down(String host, int port, String username, final String password,String src,String dir) {
        ChannelSftp sftp = null;
        Channel channel = null;
        Session sshSession = null;
        try {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            sftp.get(src,dir);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeChannel(sftp);
            closeChannel(channel);
            closeSession(sshSession);
        }
    }

    private static void closeChannel(Channel channel) {
        if (channel != null) {
            if (channel.isConnected()) {
                channel.disconnect();
            }
        }
    }

    private static void closeSession(Session session) {
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }
    // 创建文件夹,并切换到该文件夹
    // 比如: hello/test
    //最终会切换到test 文件夹返回
    private static void createDir(FTPClient client, String path) throws IOException {
        String[] dirs = path.split("/");
        for (String dir : dirs) {
            if (StringUtils.isEmpty(dir)) {
                continue;
            }
            if (!client.changeWorkingDirectory(dir)) {
                client.makeDirectory(dir);
            }
            client.changeWorkingDirectory(dir);
        }
    }

    /**
     * 服务器上的照片转换成流
     * @param url
     * @return
     */
    public InputStream pictureToInputStream(String url){
        InputStream inputStream = null;
        try {
            URL httpurl = new URL(url);
            HttpURLConnection httpURLConnection = null;
            httpURLConnection = (HttpURLConnection) httpurl.openConnection();
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET");
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                inputStream = httpURLConnection.getInputStream();
            }
            //FtpFileUtil.upload(FTP_ADDRESS,FTP_PORT,FTP_USERNAME,FTP_PASSWORD,inputStream,FTP_BASEPATH+"test");

            FileUtils.copyInputStreamToFile(inputStream, new File("E://123.jpg"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }


     /*public static  String upload(InputStream inputStream, String originName, String FTP_ADDRESS,Integer FTP_PORT,String FTP_USERNAME,String FTP_PASSWORD,String FTP_BASEPATH) {

        StringBuilder url = new StringBuilder();

        FTPClient ftp = new FTPClient();
        ftp.setControlEncoding("GBK");
        try {
            int reply;
            ftp.connect(FTP_ADDRESS, FTP_PORT);// 连接FTP服务器
            ftp.login(FTP_USERNAME, FTP_PASSWORD);// 登录
            reply = ftp.getReplyCode();
            System.out.println("reply:" + reply);

            ftp.enterLocalPassiveMode();//开启被动模式,否则文件上传不成功,也不报错

            String timePath = getTimePath();
            String saveDir = FTP_BASEPATH + timePath;
            url.append(saveDir);

            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            createDir(ftp, saveDir);
            //ftp.makeDirectory(saveDir);
            //   ftp.changeWorkingDirectory(FTP_BASEPATH);
            originName= System.currentTimeMillis()+originName.substring(originName.lastIndexOf('.'));
            url.append(originName);
            ftp.storeFile(originName, inputStream);
            inputStream.close();
            ftp.logout();

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败");
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }

        return url.toString();
    }*/
}

https://www.cnblogs.com/shangxiaofei/p/5303454.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值