sftp上傳下載文件


Maven配置

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

 

編寫工具類

public ChannelSftp getChannel(Map<String, String> sftpDetails, int timeout) throws JSchException {
     String ftpHost = sftpDetails.get(SFTPConstants.SFTP_REQ_HOST);
     String port = sftpDetails.get(SFTPConstants.SFTP_REQ_PORT);
     String ftpUserName = sftpDetails.get(SFTPConstants.SFTP_REQ_USERNAME);
     String ftpPassword = sftpDetails.get(SFTPConstants.SFTP_REQ_PASSWORD);
     int ftpPort = SFTPConstants.SFTP_DEFAULT_PORT;
     if (port != null && !port.equals("")) {
         ftpPort = Integer.valueOf(port);
    }
     JSch jsch = new JSch(); // 創建JSch對象
     session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // 根據用戶名,主機ip,端口獲取一個Session對象
     if (ftpPassword != null) {
         session.setPassword(ftpPassword); // 設置密碼
    }
     Properties config = new Properties();
     config.put("StrictHostKeyChecking", "no");//設置不用檢查HostKey,設成yes,一旦計算機的密匙發生變化,就拒絕連接。
     session.setConfig(config); // 為Session對象設置properties
     session.setTimeout(timeout); // 設置timeout時間
     session.connect(); // 通過Session建立鏈接
     channel = session.openChannel("sftp"); // 打開SFTP通道
     channel.connect(); // 建立SFTP通道的連接
     LOG.info("Connected successfully to ftpHost = " + ftpHost + ",as ftpUserName = " + ftpUserName
             + ", returning: " + channel);
     return (ChannelSftp) channel;
}

 
 public void closeChannel() throws Exception {
     if (channel != null) {
         channel.disconnect();
    }
     if (session != null) {
         session.disconnect();
    }
}

 

文件下載

public void downloadFile() {
SFTPChannel channel = null;
ChannelSftp chSftp = null;
try {
Map<String, String> sftpDetails = new HashMap<String, String>();
sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, "94.191.117.99");
sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME, "ddkx");
sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD, "ddkx");
sftpDetails.put(SFTPConstants.SFTP_REQ_PORT, "26");
channel = new SFTPChannel();
chSftp = channel.getChannel(sftpDetails, 60000);
String downPath = "D:" + File.separator + "ddrbdnl";
File localFile = new File(downPath);
if (!localFile.exists()) {
localFile.mkdirs();
}
String filename = "sftp.txt";
chSftp.get(filename, downPath);
log.info("------文件下載成功------");

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
chSftp.quit();
channel.closeChannel();
} catch (Exception e) {
e.printStackTrace();
}
}
}

 

 

文件上傳

public static void main(String[] args) throws Exception {
       SFTPTest test = new SFTPTest();

       Map<String, String> sftpDetails = new HashMap<String, String>();
       // 設置主機ip,端口,用戶名,密碼
       sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, "10.9.167.55");
       sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME, "root");
       sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD, "arthur");
       sftpDetails.put(SFTPConstants.SFTP_REQ_PORT, "22");
       
       String src = "D:\\DevSoft\\HB-SnagIt1001.rar"; // 本地文件名
       String dst = "/home/omc/ylong/sftp/HB-SnagIt1001.rar"; // 目標文件名
             
       SFTPChannel channel = test.getSFTPChannel();
       ChannelSftp chSftp = channel.getChannel(sftpDetails, 60000);
       
       /**
        * 代碼段1
       OutputStream out = chSftp.put(dst, ChannelSftp.OVERWRITE); // 使用OVERWRITE模式
       byte[] buff = new byte[1024 * 256]; // 設定每次傳輸的數據塊大小為256KB
       int read;
       if (out != null) {
           System.out.println("Start to read input stream");
           InputStream is = new FileInputStream(src);
           do {
               read = is.read(buff, 0, buff.length);
               if (read > 0) {
                   out.write(buff, 0, read);
               }
               out.flush();
           } while (read >= 0);
           System.out.println("input stream read done.");
       }
       **/
       
       chSftp.put(src, dst, ChannelSftp.OVERWRITE); // 代碼段2
       
       // chSftp.put(new FileInputStream(src), dst, ChannelSftp.OVERWRITE); // 代碼段3
       
       chSftp.quit();
       channel.closeChannel();
  }

 

監控傳輸進度

public interface SftpProgressMonitor{
 public static final int PUT=0;
 public static final int GET=1;
 void init(int op, String src, String dest, long max);
 boolean count(long count);
 void end();
}

 

實現類1

public class MyProgressMonitor implements SftpProgressMonitor {
   private long transfered;

   @Override
   public boolean count(long count) {
       transfered = transfered + count;
       System.out.println("Currently transferred total size: " + transfered + " bytes");
       return true;
  }

   @Override
   public void end() {
       System.out.println("Transferring done.");
  }

   @Override
   public void init(int op, String src, String dest, long max) {
       System.out.println("Transferring begin.");
  }
}

 

 

實現類2

public class FileProgressMonitor extends TimerTask implements SftpProgressMonitor {
   
   private long progressInterval = 5 * 1000; // 默認間隔時間為5秒
   
   private boolean isEnd = false; // 記錄傳輸是否結束
   
   private long transfered; // 記錄已傳輸的數據總大小
   
   private long fileSize; // 記錄文件總大小
   
   private Timer timer; // 定時器對象
   
   private boolean isScheduled = false; // 記錄是否已啟動timer記時器
   
   public FileProgressMonitor(long fileSize) {
       this.fileSize = fileSize;
  }
   
   @Override
   public void run() {
       if (!isEnd()) { // 判斷傳輸是否已結束
           System.out.println("Transfering is in progress.");
           long transfered = getTransfered();
           if (transfered != fileSize) { // 判斷當前已傳輸數據大小是否等於文件總大小
               System.out.println("Current transfered: " + transfered + " bytes");
               sendProgressMessage(transfered);
          } else {
               System.out.println("File transfering is done.");
               setEnd(true); // 如果當前已傳輸數據大小等於文件總大小,說明已完成,設置end
          }
      } else {
           System.out.println("Transfering done. Cancel timer.");
           stop(); // 如果傳輸結束,停止timer記時器
           return;
      }
  }
   
   public void stop() {
       System.out.println("Try to stop progress monitor.");
       if (timer != null) {
           timer.cancel();
           timer.purge();
           timer = null;
           isScheduled = false;
      }
       System.out.println("Progress monitor stoped.");
  }
   
   public void start() {
       System.out.println("Try to start progress monitor.");
       if (timer == null) {
           timer = new Timer();
      }
       timer.schedule(this, 1000, progressInterval);
       isScheduled = true;
       System.out.println("Progress monitor started.");
  }
   
   /**
    * 打印progress信息
    * @param transfered
    */
   private void sendProgressMessage(long transfered) {
       if (fileSize != 0) {
           double d = ((double)transfered * 100)/(double)fileSize;
           DecimalFormat df = new DecimalFormat( "#.##");
           System.out.println("Sending progress message: " + df.format(d) + "%");
      } else {
           System.out.println("Sending progress message: " + transfered);
      }
  }

   /**
    * 實現了SftpProgressMonitor接口的count方法
    */
   public boolean count(long count) {
       if (isEnd()) return false;
       if (!isScheduled) {
           start();
      }
       add(count);
       return true;
  }

   /**
    * 實現了SftpProgressMonitor接口的end方法
    */
   public void end() {
       setEnd(true);
       System.out.println("transfering end.");
  }
   
   private synchronized void add(long count) {
       transfered = transfered + count;
  }
   
   private synchronized long getTransfered() {
       return transfered;
  }
   
   public synchronized void setTransfered(long transfered) {
       this.transfered = transfered;
  }
   
   private synchronized void setEnd(boolean isEnd) {
       this.isEnd = isEnd;
  }
   
   private synchronized boolean isEnd() {
       return isEnd;
  }

   public void init(int op, String src, String dest, long max) {
       // Not used for putting InputStream
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM