Java代碼獲取SFTP服務器文件


與下游聯調時遇到的問題, 一般我們會使用ftp來傳遞文件, 因為sftp的傳輸效率很低. 所以為了兼容,引用了網上的方法.

步驟

  • 導入所需Jar包
  • 編寫工具類
  • 代碼中運用

 

1. 導入 Jsch-0.1.54.jar

直接去maven庫中下載即可
 

2. 編寫工具類--SFTPUtil.java

  1 /**
  2  * @author shansm
  3  * @date 2020/3/18 -17:27
  4  */
  5 public class SFTPUtil {
  6 
  7     private transient Logger log = LoggerFactory.getLogger(this.getClass());
  8 
  9     private ChannelSftp sftp;
 10 
 11     private Session session;
 12     /** SFTP 登錄用戶名*/
 13     private String username;
 14     /** SFTP 登錄密碼*/
 15     private String password;
 16     /** 私鑰 */
 17     private String privateKey;
 18     /** SFTP 服務器地址IP地址*/
 19     private String host;
 20     /** SFTP 端口*/
 21     private int port;
 22 
 23 
 24     /**
 25      * 構造基於密碼認證的sftp對象
 26      */
 27     public SFTPUtil(String username, String password, String host, int port) {
 28         this.username = username;
 29         this.password = password;
 30         this.host = host;
 31         this.port = port;
 32     }
 33 
 34     /**
 35      * 構造基於秘鑰認證的sftp對象
 36      */
 37     public SFTPUtil(String username, String host, int port, String privateKey) {
 38         this.username = username;
 39         this.host = host;
 40         this.port = port;
 41         this.privateKey = privateKey;
 42     }
 43 
 44     public SFTPUtil(){}
 45 
 46     /**
 47      * 初始化ftp參數
 48      * @param resultFileURL
 49      */
 50     public SFTPUtil(String resultFileURL , String keys) throws Exception {
 51         Map<String, String> map = URLUtil.parseSftp(resultFileURL);
 52         init(map.get("ipAddress"),map.get("ipPort"),map.get("userName"),map.get("passWord"),keys);
 53         log.info("ip: "+map.get("ipAddress"));
 54         log.info("port: "+map.get("ipPort"));
 55         log.info("userName: "+map.get("userName"));
 56         log.info("PassWord: "+map.get("passWord"));
 57     }
 58 
 59     /**初始化參數**/
 60     private void init(String ip, String portN, String userName, String passWord,String keys)
 61             throws Exception {
 62         if(StringUtils.isNotEmpty(portN)){
 63             port=Integer.parseInt(portN);
 64         }else{
 65             port = 21;
 66         }
 67 
 68         if(StringUtils.isNotEmpty(keys)){
 69             privateKey = keys;
 70         }
 71 
 72         host = new String(ip);
 73         sftp = new ChannelSftp();
 74         username = new String(userName);
 75         password = new String(passWord);
 76     }
 77 
 78 
 79     /**
 80      * 連接sftp服務器
 81      */
 82     public void login(){
 83         try {
 84             JSch jsch = new JSch();
 85             if (privateKey != null) {
 86                 jsch.addIdentity(privateKey);// 設置私鑰
 87             }
 88 
 89             session = jsch.getSession(username, host, port);
 90 
 91             if (password != null) {
 92                 session.setPassword(password);
 93             }
 94             Properties config = new Properties();
 95             config.put("StrictHostKeyChecking", "no");
 96 
 97             session.setConfig(config);
 98             session.connect();
 99 
100             Channel channel = session.openChannel("sftp");
101             channel.connect();
102 
103             sftp = (ChannelSftp) channel;
104             log.info("登陸 Sftp Server Success");
105         } catch (JSchException e) {
106             e.printStackTrace();
107             log.error(e.getMessage());
108         }
109     }
110 
111     /**
112      * 關閉連接 server
113      */
114     public void logout(){
115         if (sftp != null) {
116             if (sftp.isConnected()) {
117                 sftp.disconnect();
118             }
119         }
120         if (session != null) {
121             if (session.isConnected()) {
122                 session.disconnect();
123             }
124         }
125     }
126 
127     /**
128      * 將輸入流的數據上傳到sftp作為文件。文件完整路徑=basePath+directory
129      * @param basePath  服務器的基礎路徑
130      * @param directory  上傳到該目錄
131      * @param sftpFileName  sftp端文件名
132      */
133     public void upload(String basePath,String directory, String sftpFileName, InputStream input) throws SftpException{
134         try {
135             sftp.cd(basePath);
136             sftp.cd(directory);
137         } catch (SftpException e) {
138             //目錄不存在,則創建文件夾
139             String [] dirs=directory.split("/");
140             String tempPath=basePath;
141             for(String dir:dirs){
142                 if(null== dir || "".equals(dir)) continue;
143                 tempPath+="/"+dir;
144                 try{
145                     sftp.cd(tempPath);
146                 }catch(SftpException ex){
147                     sftp.mkdir(tempPath);
148                     sftp.cd(tempPath);
149                 }
150             }
151         }
152         sftp.put(input, sftpFileName);  //上傳文件
153     }
154 
155 
156     /**
157      * 下載文件。
158      * @param directory 下載目錄
159      * @param downloadFile 下載的文件
160      * @param saveFile 存在本地的路徑
161      */
162     public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException {
163         if (directory != null && !"".equals(directory)) {
164             sftp.cd(directory);
165         }
166         File file = new File(saveFile);
167         sftp.get(downloadFile, new FileOutputStream(file));
168     }
169 
170     /**
171      * 下載文件
172      * @param directory 下載目錄
173      * @param downloadFile 下載的文件名
174      * @return 字節數組
175      */
176     public byte[] download(String directory, String downloadFile) throws SftpException, IOException{
177         if (directory != null && !"".equals(directory)) {
178             sftp.cd(directory);
179         }
180         InputStream is = sftp.get(downloadFile);
181 
182         byte[] fileData = IOUtils.toByteArray(is);
183 
184         return fileData;
185     }
186 
187 
188     /**
189      * 刪除文件
190      * @param directory 要刪除文件所在目錄
191      * @param deleteFile 要刪除的文件
192      */
193     public void delete(String directory, String deleteFile) throws SftpException{
194         sftp.cd(directory);
195         sftp.rm(deleteFile);
196     }
197 
198 
199     /**
200      * 列出目錄下的文件
201      * @param directory 要列出的目錄
202      */
203     public Vector<?> listFiles(String directory) throws SftpException {
204         return sftp.ls(directory);
205     }
206 
207     //上傳文件測試
208     public static void main(String[] args) throws SftpException, IOException {
209         SFTPUtil sftp = new SFTPUtil("用戶名", "密碼", "ip地址", 22);
210         sftp.login();
211         File file = new File("D:\\圖片\\t0124dd095ceb042322.jpg");
212         InputStream is = new FileInputStream(file);
213 
214         sftp.upload("基礎路徑","文件路徑", "test_sftp.jpg", is);
215         sftp.logout();
216     }
217 
218     /***
219      * 獲取ftp內容
220      * @param resultFileURL
221      * @return
222      */
223     public String getFtpContent(String resultFileURL) {
224         String str=null;
225         log.info("SFTP getFtpContent Start");
226         try {
227             Map<String, String> map = URLUtil.parseSftp(resultFileURL);
228             String ipAdress = map.get("ipAddress");
229             int ipPort = SafeUtils.getInt(map.get("ipPort"),21);
230             String userName = map.get("userName");
231             String passWord = map.get("passWord");
232             log.info("sftp ipAdress="+ipAdress+",ipPort="+ipPort+",userName="+userName+",passWord="+passWord);
233             login();
234             String path = map.get("path");
235             path=path.replace("//","/"); //防止雙杠導致目錄失敗
236             log.info("ftp path="+path);
237 
238             /*String changePath = path.substring(0, path.lastIndexOf("/")+1);
239             log.info("ftp changePath="+changePath);*/
240 
241             InputStream inputStream = sftp.get(path);
242 
243             BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
244             String data = null;
245             StringBuffer resultBuffer = new StringBuffer();
246             while ((data = br.readLine()) != null) {
247                 resultBuffer.append(data + "\n");
248             }
249             str = resultBuffer.toString();
250             log.info("ftp content:"+str);
251             logout();
252         } catch (Exception e) {
253             // TODO Auto-generated catch block
254             e.printStackTrace();
255             log.error("ftp error:",e);
256         }
257         return str;
258     }
259 }

2. 調用URLUtil.java 來幫助解析Url地址

 1 public  URLUtil class{
 2     /***
 3      * 用解析sftp
 4      * @param url
 5      * @return
 6      * @throws Exception
 7      */
 8     public static Map<String, String> parseSftp(String url) throws Exception{
 9         Map<String, String> temp = new HashMap<String, String>();
10         String ipPort= "21";
11         //由於 URL類解析 sftp地址會報錯, 所以截取掉前面的s
12         url = url.substring(1);
13         URL urltemp = new URL(url);
14         String ipAddress = urltemp.getHost();
15         if (urltemp.getPort()!=-1) {
16             ipPort = urltemp.getPort()+"";
17         };
18         String path = urltemp.getPath();
19         String userInfo = urltemp.getUserInfo();
20         String userName = "";
21         String userPwd = "";
22         if(StringUtils.isNotEmpty(userInfo)){
23             String[] array = userInfo.split(":");
24             if(array.length>0){
25                 userName = array[0];
26             }
27 
28             if(array.length>=1){
29                 userPwd = array[1];
30             }
31         }
32         temp.put("userName", userName);
33         temp.put("passWord", userPwd);
34         temp.put("ipAddress", ipAddress);
35         temp.put("ipPort", ipPort);
36         temp.put("path", path);
37 
38         return temp;
39     }
40 }

 

3 代碼中調用方法

1 SFTPUtil sftpUtil = new SFTPUtil(resultFileURL,"");        //初始化工具類, 第二個參數為密鑰,沒有就不填
2 cont = sftpUtil.getFtpContent(resultFileURL);            //返回讀取的string 字符串, 根據雙方約定解析成不同格式即可

 


免責聲明!

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



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