首页 > 编程语言 > 详细

java后台上传到linux

时间:2015-11-05 18:12:56      阅读:215      评论:0      收藏:0      [点我收藏+]
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class Test {
    
    private static Logger logger = LoggerFactory.getLogger(Test.class);
    
    public static void main(String[] args) {
        String fileName = "img.jpg";
        String host = "192.168.1.1";//windos到linux用外网IP就可以,但linux上传到linux要涉及网段、防火墙等,所以这里用的是内网IP
        int port = 22;
        String username = "root";
        String password = "123456";
        try {
            InputStream is = new FileInputStream(new File("D:\\xxx\\test.jpg"));
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            Session sshSession = jsch.getSession(username, host, port);
            logger.info("创建Session……");
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            logger.info("连接Session……");
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            logger.info("连接Channel……");
            ChannelSftp sftp = (ChannelSftp) channel;

            sftp.cd("/usr/local/tomcat7/webapps/upload/");//上传时接文件的服务器的存放目录
            sftp.put(is, fileName, ChannelSftp.OVERWRITE);//有重名文件覆盖
            sshSession.disconnect();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

<dependency>
  <groupId>com.jcraft</groupId>
  <artifactId>jsch</artifactId>
  <version>0.1.50</version>
</dependency>

java后台上传到linux

原文:http://www.cnblogs.com/linying/p/4939967.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!