Java使用SFTP和FTP两种连接方式实现对服务器的上传下载

转载地址:https://blog.csdn.net/a745233700/article/details/79322757

一、Java实现对SFTP服务器的文件的上传下载

1、添加maven依赖:

  1. <dependency>
  2. <groupId>com.jcraft </groupId>
  3. <artifactId>jsch </artifactId>
  4. <version>0.1.54 </version>
  5. </dependency>

2、SFTPUtil工具类:

  1. import java.io.ByteArrayInputStream;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.UnsupportedEncodingException;
  9. import java.util.Properties;
  10. import java.util.Vector;
  11. import org.apache.commons.io.IOUtils;
  12. import org.slf4j.Logger;
  13. import org.slf4j.LoggerFactory;
  14. import com.jcraft.jsch.Channel;
  15. import com.jcraft.jsch.ChannelSftp;
  16. import com.jcraft.jsch.JSch;
  17. import com.jcraft.jsch.JSchException;
  18. import com.jcraft.jsch.Session;
  19. import com.jcraft.jsch.SftpException;
  20. /**
  21. * 类说明 sftp工具类
  22. */
  23. public class SFTPUtil {
  24. private transient Logger log = LoggerFactory.getLogger( this.getClass());
  25. private ChannelSftp sftp;
  26. private Session session;
  27. /** SFTP 登录用户名*/
  28. private String username;
  29. /** SFTP 登录密码*/
  30. private String password;
  31. /** 私钥 */
  32. private String privateKey;
  33. /** SFTP 服务器地址IP地址*/
  34. private String host;
  35. /** SFTP 端口*/
  36. private int port;
  37. /**
  38. * 构造基于密码认证的sftp对象
  39. */
  40. public SFTPUtil(String username, String password, String host, int port) {
  41. this.username = username;
  42. this.password = password;
  43. this.host = host;
  44. this.port = port;
  45. }
  46. /**
  47. * 构造基于秘钥认证的sftp对象
  48. */
  49. public SFTPUtil(String username, String host, int port, String privateKey) {
  50. this.username = username;
  51. this.host = host;
  52. this.port = port;
  53. this.privateKey = privateKey;
  54. }
  55. public SFTPUtil(){}
  56. /**
  57. * 连接sftp服务器
  58. */
  59. public void login(){
  60. try {
  61. JSch jsch = new JSch();
  62. if (privateKey != null) {
  63. jsch.addIdentity(privateKey); // 设置私钥
  64. }
  65. session = jsch.getSession(username, host, port);
  66. if (password != null) {
  67. session.setPassword(password);
  68. }
  69. Properties config = new Properties();
  70. config.put( "StrictHostKeyChecking", "no");
  71. session.setConfig(config);
  72. session.connect();
  73. Channel channel = session.openChannel( "sftp");
  74. channel.connect();
  75. sftp = (ChannelSftp) channel;
  76. } catch (JSchException e) {
  77. e.printStackTrace();
  78. }
  79. }
  80. /**
  81. * 关闭连接 server
  82. */
  83. public void logout(){
  84. if (sftp != null) {
  85. if (sftp.isConnected()) {
  86. sftp.disconnect();
  87. }
  88. }
  89. if (session != null) {
  90. if (session.isConnected()) {
  91. session.disconnect();
  92. }
  93. }
  94. }
  95. /**
  96. * 将输入流的数据上传到sftp作为文件。文件完整路径=basePath+directory
  97. * @param basePath 服务器的基础路径
  98. * @param directory 上传到该目录
  99. * @param sftpFileName sftp端文件名
  100. * @param in 输入流
  101. */
  102. public void upload(String basePath,String directory, String sftpFileName, InputStream input) throws SftpException{
  103. try {
  104. sftp.cd(basePath);
  105. sftp.cd(directory);
  106. } catch (SftpException e) {
  107. //目录不存在,则创建文件夹
  108. String [] dirs=directory.split( "/");
  109. String tempPath=basePath;
  110. for(String dir:dirs){
  111. if( null== dir || "".equals(dir)) continue;
  112. tempPath+= "/"+dir;
  113. try{
  114. sftp.cd(tempPath);
  115. } catch(SftpException ex){
  116. sftp.mkdir(tempPath);
  117. sftp.cd(tempPath);
  118. }
  119. }
  120. }
  121. sftp.put(input, sftpFileName); //上传文件
  122. }
  123. /**
  124. * 下载文件。
  125. * @param directory 下载目录
  126. * @param downloadFile 下载的文件
  127. * @param saveFile 存在本地的路径
  128. */
  129. public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException{
  130. if (directory != null && ! "".equals(directory)) {
  131. sftp.cd(directory);
  132. }
  133. File file = new File(saveFile);
  134. sftp.get(downloadFile, new FileOutputStream(file));
  135. }
  136. /**
  137. * 下载文件
  138. * @param directory 下载目录
  139. * @param downloadFile 下载的文件名
  140. * @return 字节数组
  141. */
  142. public byte[] download(String directory, String downloadFile) throws SftpException, IOException{
  143. if (directory != null && ! "".equals(directory)) {
  144. sftp.cd(directory);
  145. }
  146. InputStream is = sftp.get(downloadFile);
  147. byte[] fileData = IOUtils.toByteArray(is);
  148. return fileData;
  149. }
  150. /**
  151. * 删除文件
  152. * @param directory 要删除文件所在目录
  153. * @param deleteFile 要删除的文件
  154. */
  155. public void delete(String directory, String deleteFile) throws SftpException{
  156. sftp.cd(directory);
  157. sftp.rm(deleteFile);
  158. }
  159. /**
  160. * 列出目录下的文件
  161. * @param directory 要列出的目录
  162. * @param sftp
  163. */
  164. public Vector<?> listFiles(String directory) throws SftpException {
  165. return sftp.ls(directory);
  166. }
  167. //上传文件测试
  168. public static void main(String[] args) throws SftpException, IOException {
  169. SFTPUtil sftp = new SFTPUtil( "用户名", "密码", "ip地址", 22);
  170. sftp.login();
  171. File file = new File( "D:\\图片\\t0124dd095ceb042322.jpg");
  172. InputStream is = new FileInputStream(file);
  173. sftp.upload( "基础路径", "文件路径", "test_sftp.jpg", is);
  174. sftp.logout();
  175. }
  176. }


二、Java实现对FTP服务器的文件的上传下载

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import org.apache.commons.net.ftp.FTP;
  9. import org.apache.commons.net.ftp.FTPClient;
  10. import org.apache.commons.net.ftp.FTPFile;
  11. import org.apache.commons.net.ftp.FTPReply;
  12. /**
  13. * ftp上传下载工具类
  14. */
  15. public class FtpUtil {
  16. /**
  17. * Description: 向FTP服务器上传文件
  18. * @param host FTP服务器hostname
  19. * @param port FTP服务器端口
  20. * @param username FTP登录账号
  21. * @param password FTP登录密码
  22. * @param basePath FTP服务器基础目录
  23. * @param filePath FTP服务器文件存放路径。文件的路径为basePath+filePath
  24. * @param filename 上传到FTP服务器上的文件名
  25. * @param input 输入流
  26. * @return 成功返回true,否则返回false
  27. */
  28. public static boolean uploadFile(String host, int port, String username, String password, String basePath,
  29. String filePath, String filename, InputStream input) {
  30. boolean result = false;
  31. FTPClient ftp = new FTPClient();
  32. try {
  33. int reply;
  34. ftp.connect(host, port); // 连接FTP服务器
  35. // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
  36. ftp.login(username, password); // 登录
  37. reply = ftp.getReplyCode();
  38. if (!FTPReply.isPositiveCompletion(reply)) {
  39. ftp.disconnect();
  40. return result;
  41. }
  42. //切换到上传目录
  43. if (!ftp.changeWorkingDirectory(basePath+filePath)) {
  44. //如果目录不存在创建目录
  45. String[] dirs = filePath.split( "/");
  46. String tempPath = basePath;
  47. for (String dir : dirs) {
  48. if ( null == dir || "".equals(dir)) continue;
  49. tempPath += "/" + dir;
  50. if (!ftp.changeWorkingDirectory(tempPath)) { //进不去目录,说明该目录不存在
  51. if (!ftp.makeDirectory(tempPath)) { //创建目录
  52. //如果创建文件目录失败,则返回
  53. System.out.println( "创建文件目录"+tempPath+ "失败");
  54. return result;
  55. } else {
  56. //目录存在,则直接进入该目录
  57. ftp.changeWorkingDirectory(tempPath);
  58. }
  59. }
  60. }
  61. }
  62. //设置上传文件的类型为二进制类型
  63. ftp.setFileType(FTP.BINARY_FILE_TYPE);
  64. //上传文件
  65. if (!ftp.storeFile(filename, input)) {
  66. return result;
  67. }
  68. input.close();
  69. ftp.logout();
  70. result = true;
  71. } catch (IOException e) {
  72. e.printStackTrace();
  73. } finally {
  74. if (ftp.isConnected()) {
  75. try {
  76. ftp.disconnect();
  77. } catch (IOException ioe) {
  78. }
  79. }
  80. }
  81. return result;
  82. }
  83. /**
  84. * Description: 从FTP服务器下载文件
  85. * @param host FTP服务器hostname
  86. * @param port FTP服务器端口
  87. * @param username FTP登录账号
  88. * @param password FTP登录密码
  89. * @param remotePath FTP服务器上的相对路径
  90. * @param fileName 要下载的文件名
  91. * @param localPath 下载后保存到本地的路径
  92. * @return
  93. */
  94. public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
  95. String fileName, String localPath) {
  96. boolean result = false;
  97. FTPClient ftp = new FTPClient();
  98. try {
  99. int reply;
  100. ftp.connect(host, port);
  101. // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
  102. ftp.login(username, password); // 登录
  103. reply = ftp.getReplyCode();
  104. if (!FTPReply.isPositiveCompletion(reply)) {
  105. ftp.disconnect();
  106. return result;
  107. }
  108. ftp.changeWorkingDirectory(remotePath); // 转移到FTP服务器目录
  109. FTPFile[] fs = ftp.listFiles();
  110. for (FTPFile ff : fs) {
  111. if (ff.getName().equals(fileName)) {
  112. File localFile = new File(localPath + "/" + ff.getName());
  113. OutputStream is = new FileOutputStream(localFile);
  114. ftp.retrieveFile(ff.getName(), is);
  115. is.close();
  116. }
  117. }
  118. ftp.logout();
  119. result = true;
  120. } catch (IOException e) {
  121. e.printStackTrace();
  122. } finally {
  123. if (ftp.isConnected()) {
  124. try {
  125. ftp.disconnect();
  126. } catch (IOException ioe) {
  127. }
  128. }
  129. }
  130. return result;
  131. }
  132. //ftp上传文件测试main函数
  133. public static void main(String[] args) {
  134. try {
  135. FileInputStream in= new FileInputStream( new File( "D:\\Tomcat 5.5\\pictures\\t0176ee418172932841.jpg"));
  136. boolean flag = uploadFile( "192.168.111.128", 21, "用户名", "密码", "/www/images", "/2017/11/19", "hello.jpg", in);
  137. System.out.println(flag);
  138. } catch (FileNotFoundException e) {
  139. e.printStackTrace();
  140. }
  141. }
  142. }

猜你喜欢

转载自blog.csdn.net/m0_38053538/article/details/80902965