---
title: "转：JAVA实现SFTP上传，下载，删除等方法"
author: "so_fast"
date: "2013-12-26T10:33:40Z"
tags: []
categories: ["Web前端"]
slug: "java-sftp"
draft: false
lastmod: "2013-12-26T10:33:40Z"
id: 1995616
url: "https://so-fast.iteye.com/blog/1995616"
---

001. **原载：http://blog.csdn.net/haidage/article/details/6859716**
002. import java.io.File;
003. import java.io.FileInputStream;
004. import java.io.FileNotFoundException;
005. import java.io.FileOutputStream;
006. import java.io.IOException;
007. import java.io.InputStream;
008. import java.io.InputStreamReader;
009. import java.io.LineNumberReader;
010. import java.util.ArrayList;
011. import java.util.List;
012. import java.util.Properties;
013. import com.jcraft.jsch.Channel;
014. import com.jcraft.jsch.ChannelSftp;
015. import com.jcraft.jsch.JSch;
016. import com.jcraft.jsch.Session;
017. import com.jcraft.jsch.SftpException;
018. public class SFTPUtil {
019. private String host = "127.0.0.1";
020. private String username="MingMac";
021. private String password="×××";
022. private int port = 22;
023. private ChannelSftp sftp = null;
024. private String localPath = "/var/test";
025. private String remotePath = "/var/tset";
026. private String fileListPath = "/var/test/java/test.txt";
027. private final String seperator = "/";
028. /\**
029. * connect server via sftp
030. \*/
031. public void connect() {
032. try {
033. if(sftp != null){
034. System.out.println("sftp is not null");
035. }
036. JSch jsch = new JSch();
037. jsch.getSession(username, host, port);
038. Session sshSession = jsch.getSession(username, host, port);
039. System.out.println("Session created.");
040. sshSession.setPassword(password);
041. Properties sshConfig = new Properties();
042. sshConfig.put("StrictHostKeyChecking", "no");
043. sshSession.setConfig(sshConfig);
044. sshSession.connect();
045. System.out.println("Session connected.");
046. System.out.println("Opening Channel.");
047. Channel channel = sshSession.openChannel("sftp");
048. channel.connect();
049. sftp = (ChannelSftp) channel;
050. System.out.println("Connected to " + host + ".");
051. } catch (Exception e) {
052. e.printStackTrace();
053. }
054. }
055. /\**
056. * Disconnect with server
057. \*/
058. public void disconnect() {
059. if(this.sftp != null){
060. if(this.sftp.isConnected()){
061. this.sftp.disconnect();
062. }else if(this.sftp.isClosed()){
063. System.out.println("sftp is closed already");
064. }
065. }
066. }
067. public void download() {
068. // TODO Auto-generated method stub
069. }
070. private void download(String directory, String downloadFile,String saveFile, ChannelSftp sftp) {
071. try {
072. sftp.cd(directory);
073. File file = new File(saveFile);
074. sftp.get(downloadFile, new FileOutputStream(file));
075. } catch (Exception e) {
076. e.printStackTrace();
077. }
078. }
079. /\**
080. * upload all the files to the server
081. \*/
082. public void upload() {
083. List&lt;String&gt; fileList = this.getFileEntryList(fileListPath);
084. try {
085. if(fileList != null){
086. for (String filepath : fileList) {
087. String localFile = this.localPath + this.seperator+ filepath;
088. File file = new File(localFile);
089. if(file.isFile()){
090. System.out.println("localFile : " + file.getAbsolutePath());
091. String remoteFile = this.remotePath + this.seperator + filepath;
092. System.out.println("remotePath:" + remoteFile);
093. File rfile = new File(remoteFile);
094. String rpath = rfile.getParent();
095. try {
096. createDir(rpath, sftp);
097. } catch (Exception e) {
098. System.out.println("\*\*\*\*\*\*\*create path failed" + rpath);
099. }
100. this.sftp.put(new FileInputStream(file), file.getName());
101. System.out.println("=========upload down for " + localFile);
102. }
103. }
104. }
105. } catch (FileNotFoundException e) {
106. // TODO Auto-generated catch block
107. e.printStackTrace();
108. } catch (SftpException e) {
109. // TODO Auto-generated catch block
110. e.printStackTrace();
111. }
112. }
113. /\**
114. * create Directory
115. * @param filepath
116. * @param sftp
117. \*/
118. private void createDir(String filepath, ChannelSftp sftp){
119. boolean bcreated = false;
120. boolean bparent = false;
121. File file = new File(filepath);
122. String ppath = file.getParent();
123. try {
124. this.sftp.cd(ppath);
125. bparent = true;
126. } catch (SftpException e1) {
127. bparent = false;
128. }
129. try {
130. if(bparent){
131. try {
132. this.sftp.cd(filepath);
133. bcreated = true;
134. } catch (Exception e) {
135. bcreated = false;
136. }
137. if(!bcreated){
138. this.sftp.mkdir(filepath);
139. bcreated = true;
140. }
141. return;
142. }else{
143. createDir(ppath,sftp);
144. this.sftp.cd(ppath);
145. this.sftp.mkdir(filepath);
146. }
147. } catch (SftpException e) {
148. System.out.println("mkdir failed :" + filepath);
149. e.printStackTrace();
150. }
151. try {
152. this.sftp.cd(filepath);
153. } catch (SftpException e) {
154. e.printStackTrace();
155. System.out.println("can not cd into :" + filepath);
156. }
157. }
158. /\**
159. * get all the files need to be upload or download
160. * @param file
161. * @return
162. \*/
163. private List&lt;String&gt; getFileEntryList(String file){
164. ArrayList&lt;String&gt; fileList = new ArrayList&lt;String&gt;();
165. InputStream in = null;
166. try {
167. in = new FileInputStream(file);
168. InputStreamReader inreader = new InputStreamReader(in);
169. LineNumberReader linreader = new LineNumberReader(inreader);
170. String filepath = linreader.readLine();
171. while(filepath != null){
172. fileList.add(filepath);
173. filepath = linreader.readLine();
174. }
175. in.close();
176. } catch (FileNotFoundException e) {
177. // TODO Auto-generated catch block
178. e.printStackTrace();
179. } catch (IOException e) {
180. // TODO Auto-generated catch block
181. e.printStackTrace();
182. }finally{
183. if(in != null){
184. in = null;
185. }
186. }
187. return fileList;
188. }
189. /\**
190. * @return the host
191. \*/
192. public String getHost() {
193. return host;
194. }
195. /\**
196. * @param host the host to set
197. \*/
198. public void setHost(String host) {
199. this.host = host;
200. }
201. /\**
202. * @return the username
203. \*/
204. public String getUsername() {
205. return username;
206. }
207. /\**
208. * @param username the username to set
209. \*/
210. public void setUsername(String username) {
211. this.username = username;
212. }
213. /\**
214. * @return the password
215. \*/
216. public String getPassword() {
217. return password;
218. }
219. /\**
220. * @param password the password to set
221. \*/
222. public void setPassword(String password) {
223. this.password = password;
224. }
225. /\**
226. * @return the port
227. \*/
228. public int getPort() {
229. return port;
230. }
231. /\**
232. * @param port the port to set
233. \*/
234. public void setPort(int port) {
235. this.port = port;
236. }
237. /\**
238. * @return the sftp
239. \*/
240. public ChannelSftp getSftp() {
241. return sftp;
242. }
243. /\**
244. * @param sftp the sftp to set
245. \*/
246. public void setSftp(ChannelSftp sftp) {
247. this.sftp = sftp;
248. }
249. /\**
250. * @return the localPath
251. \*/
252. public String getLocalPath() {
253. return localPath;
254. }
255. /\**
256. * @param localPath the localPath to set
257. \*/
258. public void setLocalPath(String localPath) {
259. this.localPath = localPath;
260. }
261. /\**
262. * @return the remotePath
263. \*/
264. public String getRemotePath() {
265. return remotePath;
266. }
267. /\**
268. * @param remotePath the remotePath to set
269. \*/
270. public void setRemotePath(String remotePath) {
271. this.remotePath = remotePath;
272. }
273. /\**
274. * @return the fileListPath
275. \*/
276. public String getFileListPath() {
277. return fileListPath;
278. }
279. /\**
280. * @param fileListPath the fileListPath to set
281. \*/
282. public void setFileListPath(String fileListPath) {
283. this.fileListPath = fileListPath;
284. }
285. public static void main(String\[] args) {
286. // TODO Auto-generated method stub
287. SFTPUtil ftp= new SFTPUtil();
288. ftp.connect();
289. ftp.upload();
290. ftp.disconnect();
291. System.exit(0);
292. }
293. }