1. 程式人生 > >利用Sftp連線伺服器上傳檔案

利用Sftp連線伺服器上傳檔案

最近專案碰到  要同步一個檔案到另一臺伺服器。借用了前輩的工具類做了點修改。記錄下來,方便以後查閱。

package com.sitech.billing.framework.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

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;


public class SftpUploadFile {
	/**
	 * 密碼方式登入 sftp
	 * @param ip 伺服器ip
	 * @param user 伺服器使用者名稱
	 * @param psw  伺服器密碼
	 * @param port 埠
	 * @param sPath 原始路徑
	 * @param dPath 目標路徑
	 * @throws Exception
	 */
    public static void sshSftp(String ip, String user, String psw, int port,
            String sPath, String dPath) throws Exception {
        System.out.println("password login");
        Session session = 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(300000);
            Channel channel = (Channel) session.openChannel("sftp");
            channel.connect(10000000);
            ChannelSftp sftp = (ChannelSftp) channel;
            //複製檔案
            upLoadFile(sftp,sPath,dPath);
            System.out.println("success");
    }
    
	 public static void upLoadFile(ChannelSftp sftp, String sPath, String dPath) {
		 	Date date=new Date();
			SimpleDateFormat format=new SimpleDateFormat("yyyyMMdd");
			File file = new File(sPath);
			String pwd = null;
            try {
            	pwd = sftp.pwd();
				pwd += "/"+dPath;
                sftp.cd(pwd);
			} catch (SftpException e) {
				e.printStackTrace();
			}
            System.out.println("正在複製檔案:" + file.getAbsolutePath());
            InputStream instream = null;
            OutputStream outstream = null;
            try {
            	//檔案按規範命名
    			String upfilename = "0002_CJFF_" +format.format(date)+ ".txt";
                outstream = sftp.put(upfilename);
                instream = new FileInputStream(file);
                byte b[] = new byte[1024];
                int n;
                try {
                    while ((n = instream.read(b)) != -1) {
                        outstream.write(b, 0, n);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
             System.out.println(pwd+"/"+upfilename+"檔案複製完成");   
            } catch (SftpException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    outstream.flush();
                    outstream.close();
                    instream.close();

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