两种ftp使用java的实现方式 ,代码都已测试

第一种:Serv-U FTP

先决条件:

1、Serv-U FTP服务器搭建成功。

2、jar包需要:版本不限制

  1. <!--ftp上传需要的jar-->
    <dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>1.4.1</version>
    </dependency>
  2.  
  3. 实现代码:
  1. import org.apache.commons.net.ftp.FTPClient;
  2. import org.apache.commons.net.ftp.FTPReply;
  3.  
  4. import javax.swing.*;
  5. import java.io.*;
  6. import java.net.SocketException;
  7.  
  8. public class FtpUtil {
  9.  
  10. private static FTPClient ftpClient = new FTPClient();
  11.  
  12. /**
  13. * 获取FTPClient对象
  14. *
  15. * @param ftpHost FTP主机服务器
  16. * @param ftpPassword FTP 登录密码
  17. * @param ftpUserName FTP登录用户名
  18. * @param ftpPort FTP端口 默认为21
  19. * @return
  20. */
  21. public FTPClient getFTPClient(String ftpHost, String ftpUserName,
  22. String ftpPassword, int ftpPort) {
  23.  
  24. try {
  25.  
  26. ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
  27. ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
  28. if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
  29. System.out.println("未连接到FTP,用户名或密码错误。");
  30. ftpClient.disconnect();
  31. } else {
  32. System.out.println("FTP连接成功。");
  33. }
  34. } catch (SocketException e) {
  35. e.printStackTrace();
  36. System.out.println("FTP的IP地址可能错误,请正确配置。");
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. System.out.println("FTP的端口错误,请正确配置。");
  40. }
  41. return ftpClient;
  42. }
  43.  
  44. /**
  45. * 从FTP服务器下载文件
  46. * @param ftpPath FTP服务器中文件所在路径
  47. * @param localPath 下载到本地的位置
  48. * @param fileName 文件名称
  49. */
  50. public void downloadFtpFile( String ftpPath, String localPath,
  51. String fileName) {
  52.  
  53. try {
  54.  
  55. ftpClient.setControlEncoding("UTF-8"); // 中文支持
  56. ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
  57. ftpClient.enterLocalPassiveMode();
  58. ftpClient.changeWorkingDirectory(ftpPath);
  59.  
  60. File localFile = new File(localPath + File.separatorChar + fileName);
  61. OutputStream os = new FileOutputStream(localFile);
  62. ftpClient.retrieveFile(fileName, os);
  63. os.close();
  64. ftpClient.logout();
  65.  
  66. } catch (FileNotFoundException e) {
  67. System.out.println("没有找到" + ftpPath + "文件");
  68. e.printStackTrace();
  69. } catch (SocketException e) {
  70. System.out.println("连接FTP失败.");
  71. e.printStackTrace();
  72. } catch (IOException e) {
  73. e.printStackTrace();
  74. System.out.println("文件读取错误。");
  75. e.printStackTrace();
  76. }
  77.  
  78. }
  79.  
  80. /**
  81. * Description: 向FTP服务器上传文件
  82. * @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa
  83. * @param fileName ftp文件名称
  84. * @param input 文件流
  85. * @return 成功返回true,否则返回false
  86. */
  87. public boolean uploadFile( String ftpPath,
  88. String fileName,InputStream input) {
  89. boolean success = false;
  90.  
  91. try {
  92. int reply;
  93.  
  94. reply = ftpClient.getReplyCode();
  95. if (!FTPReply.isPositiveCompletion(reply)) {
  96. ftpClient.disconnect();
  97. return success;
  98. }
  99. ftpClient.setControlEncoding("UTF-8"); // 中文支持
  100. ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
  101. ftpClient.enterLocalPassiveMode();
  102. ftpClient.changeWorkingDirectory(ftpPath);
  103.  
  104. ftpClient.storeFile(fileName, input);
  105.  
  106. input.close();
  107. ftpClient.logout();
  108. success = true;
  109. } catch (IOException e) {
  110. e.printStackTrace();
  111. } finally {
  112. if (ftpClient.isConnected()) {
  113. try {
  114. ftpClient.disconnect();
  115. } catch (IOException ioe) {
  116. }
  117. }
  118. }
  119. return success;
  120. }
  121.  
  122. public static void main(String args[]){
  123.  
  124. String ftpHost = "127.0.0.1";
  125. String ftpUserName = "servUFtp";
  126. String ftpPassword = "14oioppii";
  127. Integer port = 21;
  128. String ftpPath = "/";
  129. String localPath = "F:\\";
  130. String fileName = "text.jpg";
  131. //上传一个文件
  132. try{
  133.  
  134. FileInputStream in=new FileInputStream(new File(localPath));
  135. FtpUtil ftpUtil = new FtpUtil();
  136.  
  137. ftpUtil.getFTPClient(ftpHost, ftpUserName, ftpPassword, port);
  138. // 上传文件
  139. boolean flag = ftpUtil.uploadFile( ftpPath, fileName,in);
  140. // 下载文件
  141. ftpUtil.downloadFtpFile( "/000.jpg", localPath, fileName);
  142. if(flag){
  143. System.out.println("文件上传ftp成功,请检查ftp服务器。");
  144.  
  145. }else{
  146. System.out.println("文件上传ftp异常。请重试!");
  147.  
  148. }
  149. } catch (FileNotFoundException e){
  150. e.printStackTrace();
  151. System.out.println(e);
  152. }
  153. }
  154.  
  155. }

第二种:SFTP

先决条件:

1、SFTP服务器搭建成功

2、jar需要:版本不限

  1. <!--sftp上传需要的jar-->
    <dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
    </dependency>
  2.  
  3. 实现代码:
  1. import com.jcraft.jsch.*;
  2.  
  3. import java.io.*;
  4. import java.util.Properties;
  5.  
  6. /**
  7. * @Author : guoyanan
  8. * @Title : Sftp工具类
  9. * @Time : 2019/04/18 14:52
  10. * @Document : 提供文件上传功能
  11. */
  12. public class SFtpUtils {
  13.  
  14. // 初始化单例对象
  15. private static SFtpUtils sFtpUtils = new SFtpUtils();
  16. private String host;//服务器连接ip
  17. private String username;//用户名
  18. private String password;//密码
  19. private int port = 22;//端口号
  20. private ChannelSftp sftp = null;
  21. private Session sshSession = null;
  22.  
  23. /**
  24. * 初始化sftp的单例对象
  25. * @return
  26. */
  27. public static SFtpUtils getInstance()
  28. {
  29. return sFtpUtils;
  30. }
  31.  
  32. /**
  33. * 初始化sft链接信息,必须先做这个
  34. * @param host 远程主机ip
  35. * @param port 端口号
  36. * @param username 账号
  37. * @param password 密码
  38. */
  39. public void init(String host, int port, String username, String password)
  40. {
  41. this.host = host;
  42. this.username = username;
  43. this.password = password;
  44. this.port = port;
  45.  
  46. }
  47.  
  48. /**
  49. * 通过SFTP连接服务器
  50. */
  51. public void connect()
  52. {
  53. try
  54. {
  55. JSch jsch = new JSch();
  56. jsch.getSession(username, host, port);
  57. sshSession = jsch.getSession(username, host, port);
  58. sshSession.setPassword(password);
  59. Properties sshConfig = new Properties();
  60. sshConfig.put("StrictHostKeyChecking", "no");
  61. sshSession.setConfig(sshConfig);
  62. sshSession.connect();
  63. Channel channel = sshSession.openChannel("sftp");
  64. channel.connect();
  65. sftp = (ChannelSftp) channel;
  66.  
  67. }
  68. catch (Exception e)
  69. {
  70. e.printStackTrace();
  71. }
  72. }
  73.  
  74. /**
  75. * 关闭连接
  76. */
  77. public void disconnect()
  78. {
  79. if (this.sftp != null)
  80. {
  81. if (this.sftp.isConnected())
  82. {
  83. this.sftp.disconnect();
  84.  
  85. }
  86. }
  87. if (this.sshSession != null)
  88. {
  89. if (this.sshSession.isConnected())
  90. {
  91. this.sshSession.disconnect();
  92.  
  93. }
  94. }
  95. }
  96.  
  97. /**
  98. * sftp下载文件
  99. * @param remoteFielPath 远程文件路径
  100. * @param localFilePath 本地下载路径
  101. * @return
  102. * @throws SftpException
  103. * @throws FileNotFoundException
  104. */
  105. public boolean downLoadFile(String remoteFielPath,String localFilePath) throws SftpException, FileNotFoundException {
  106. // 检查文件是否存在
  107. SftpATTRS sftpATTRS = sftp.lstat(remoteFielPath);
  108. if(!sftpATTRS.isReg()){
  109. // 不是一个文件,返回false
  110. return false;
  111. }
  112. // 下载文件到本地
  113. sftp.get(remoteFielPath,localFilePath);
  114.  
  115. return true;
  116. }
  117.  
  118. /**
  119. * 下载文件放回文件数据
  120. * @param remoteFielPath
  121. * @return
  122. * @throws SftpException
  123. * @throws IOException
  124. */
  125. public boolean downLoadFileTwo(String remoteFielPath, String localFilePath) throws SftpException, IOException {
  126. // 检查文件是否存在
  127. SftpATTRS sftpATTRS = sftp.lstat(remoteFielPath);
  128. // 判断是否是一个文件
  129. if(sftpATTRS.isReg()){
  130. // 下载文件到本地
  131. InputStream inputStream = sftp.get(remoteFielPath);
  132. /**今天想写下从sftp下载文件到本地,虽然sftp提供了get(String remotePath,String LocalPath)方法,将远程文件写入到本地。
  133. * 但还是想属性下从远程获取InputStream对象写入到本地的方式。
  134. * 遇到的问题:刚开始只想这实现,就是获取byte对象写入到本地文件,先用ByteArrayInputStream怎么转都无法获取到bytes对象
  135. * 放入到FileOutputStream对象中。搞了老半天都没有搞定,或许有ByteArrayInputStream对象下载的方式但没有找到。
  136. * 正解:如下*/
  137. // 通过BufferedInputStream对象缓存输入流对象获取远程的输入流
  138. BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
  139. // 创建本地文件信息
  140. File file = new File("F:\\456.jpg");
  141. // 将本地文件放入到 本地文件输出流
  142. FileOutputStream fileOutputStream = new FileOutputStream(file);
  143. // 将本地文件输出流 放入到 缓存输出流对象
  144. BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
  145. // 声明每次获取的byte长度
  146. int len = 2048;
  147. // 初始化byte[]
  148. byte[] bytes = new byte[len];
  149. /**通过BufferedInputStream对象获取 远程文件 InputStream的bytes字节信息,并循环添加到BufferedOutputStream缓存输出流对象中,
  150. * 将远程bytes数据写入到本地文件中
  151. * 遇到的问题:这里我一直纠结于为什么这样写会实现想要的效果,是如何写入到本地的
  152. * 其实这不是开发中遇到的问题的事情了,是自己困于自己设定的一个纠结情绪中了。也就是俗称的牛角尖。
  153. * 切记,一定不可以钻牛角尖。因为开发都是有语言规则的。按照规则来就能实现效果,脱离规则即使神仙也无能为力。
  154. * */
  155. while ((len = bufferedInputStream.read(bytes)) != -1){
  156. bufferedOutputStream.write(bytes,0,len);
  157. }
  158. bufferedOutputStream.flush();
  159. bufferedInputStream.close();
  160. bufferedOutputStream.close();
  161. fileOutputStream.close();
  162. inputStream.close();
  163. return true;
  164. }
  165. return false;
  166.  
  167. }
  168. /**
  169. * 上传单个文件,通过文件路径上传
  170. * @param remotePath:远程保存目录
  171. * @param remoteFileName:保存文件名
  172. * @param localPath:本地上传目录(以路径符号结束)
  173. * @param localFileName:上传的文件名
  174. * @return
  175. */
  176. public boolean uploadFile(String remotePath, String remoteFileName,String localPath, String localFileName)
  177. {
  178. FileInputStream in = null;
  179. try
  180. { // 创建目录
  181. createDir(remotePath);
  182. File file = new File(localPath + localFileName);
  183. in = new FileInputStream(file);
  184. sftp.put(in, remoteFileName);
  185. return true;
  186. }catch (FileNotFoundException e)
  187. {
  188. e.printStackTrace();
  189. }catch (SftpException e)
  190. {
  191. e.printStackTrace();
  192. }
  193. finally
  194. {
  195. if (in != null)
  196. {
  197. try
  198. {
  199. in.close();
  200. }
  201. catch (IOException e)
  202. {
  203. e.printStackTrace();
  204. }
  205. }
  206. }
  207. return false;
  208. }
  209.  
  210. /**
  211. * 上传文件到sftp,通过输入流上传
  212. * @param remotePath
  213. * @param remoteFileName
  214. * @param inputStream
  215. * @return
  216. */
  217. public boolean uploadFile(String remotePath, String remoteFileName,InputStream inputStream)
  218. {
  219. FileInputStream in = null;
  220. try
  221. { // 创建目录
  222. createDir(remotePath);
  223. sftp.put(inputStream, remoteFileName);
  224. return true;
  225. }catch (SftpException e)
  226. {
  227. e.printStackTrace();
  228. }
  229. finally
  230. {
  231. if (in != null)
  232. {
  233. try
  234. {
  235. in.close();
  236. }
  237. catch (IOException e)
  238. {
  239. e.printStackTrace();
  240. }
  241. }
  242. }
  243. return false;
  244. }
  245.  
  246. /**
  247. * 创建目录
  248. * @param createpath
  249. * @return
  250. */
  251. public boolean createDir(String createpath)
  252. {
  253. try
  254. {
  255. if (isDirExist(createpath))
  256. {
  257. // 有时候,开发在填写路径的时候第一个位置会忘记加"/"的根路径
  258. // 这回引发cd操作是发生:NO Such File 异常,所以这里处理下
  259. if(!(createpath.substring(0,1)=="/")){
  260. createpath="/"+createpath;
  261. }
  262. this.sftp.cd(createpath);
  263. return true;
  264. }
  265. String pathArry[] = createpath.split("/");
  266. StringBuffer filePath = new StringBuffer("/");
  267. for (String path : pathArry)
  268. {
  269. if (path.equals(""))
  270. {
  271. continue;
  272. }
  273. filePath.append(path + "/");
  274. if (isDirExist(filePath.toString()))
  275. {
  276. sftp.cd(filePath.toString());
  277. }
  278. else
  279. {
  280. // 建立目录
  281. sftp.mkdir(filePath.toString());
  282. // 进入并设置为当前目录
  283. sftp.cd(filePath.toString());
  284. }
  285.  
  286. }
  287. this.sftp.cd(createpath);
  288. return true;
  289. }
  290. catch (SftpException e)
  291. {
  292. e.printStackTrace();
  293. }
  294. return false;
  295. }
  296.  
  297. /**
  298. * 判断目录是否存在,linux目录必须最前方带有"/"
  299. * @param directory
  300. * @return
  301. */
  302. public boolean isDirExist(String directory)
  303. {
  304. boolean isDirExistFlag = false;
  305. try
  306. {
  307. // 有时候,开发在填写路径的时候第一个位置会忘记加"/"的根路径
  308. // 这回引发cd操作是发生:NO Such File 异常,所以这里处理下
  309. if(!(directory.substring(0,1)=="/")){
  310. directory="/"+directory;
  311. }
  312. SftpATTRS sftpATTRS = sftp.lstat(directory);
  313. isDirExistFlag = true;
  314. return sftpATTRS.isDir();
  315. }
  316. catch (Exception e)
  317. {
  318. if (e.getMessage().toLowerCase().equals("no such file"))
  319. {
  320. isDirExistFlag = false;
  321. }
  322. }
  323. return isDirExistFlag;
  324. }
  325.  
  326. public static void main(String arg[]) throws IOException, SftpException {
  327. // 获取图片的InputStream对象,并将图片生成到sftp上
  328. SFtpUtils sFtpUtils= SFtpUtils.getInstance();
  329. sFtpUtils.init("127.0.0.1",22, "sftpuser", "UIOPOopi");
  330. sFtpUtils.connect();
  331. // 上传文件
  332. /*File file = new File("F:\\OK.jpg");
  333. InputStream in = new FileInputStream(file);
  334. boolean flag = sFtpUtils.uploadFile("/app/xwapp/Test","1111.jpg",in);*/
  335.  
  336. // 下载文件到本地方法1
  337. // boolean flag = sFtpUtils.downLoadFile("/app/xwapp/Test/1111.jpg","F:\\OKbak.jpg");
  338. // 下载文件到本地方法2
  339. boolean flag = sFtpUtils.downLoadFileTwo("/app/xwapp/Test/1111.jpg","F:\\OKbak.jpg");
  340. if(flag){
  341. System.out.println("处理成功");
  342. }else {
  343. System.out.println("处理失败");
  344. }
  345. sFtpUtils.disconnect();
  346. }
  347. }

java 实现Serv-U FTP 和 SFTP 上传 下载的更多相关文章

  1. java:工具(汉语转拼音,压缩包,EXCEL,JFrame窗口和文件选择器,SFTP上传下载,FTP工具类,SSH)

    1.汉语转拼音: import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuP ...

  2. Java Sftp上传下载文件

    需要使用jar包  jsch-0.1.50.jar sftp上传下载实现类 package com.bstek.transit.sftp; import java.io.File; import ja ...

  3. THINKPHP 3.2 PHP SFTP上传下载 代码实现方法

     一.SFTP介绍:使用SSH协议进行FTP传输的协议叫SFTP(安全文件传输)Sftp和Ftp都是文件传输协议.区别:sftp是ssh内含的协议(ssh是加密的telnet协议),  只要sshd服 ...

  4. Xshell5下利用sftp上传下载传输文件

    sftp是Secure File Transfer Protocol的缩写,安全文件传送协议.可以为传输文件提供一种安全的加密方法.sftp 与 ftp 有着几乎一样的语法和功能.SFTP 为 SSH ...

  5. SFTP上传下载文件、文件夹常用操作

    SFTP上传下载文件.文件夹常用操作 1.查看上传下载目录lpwd 2.改变上传和下载的目录(例如D盘):lcd  d:/ 3.查看当前路径pwd 4.下载文件(例如我要将服务器上tomcat的日志文 ...

  6. python使用ftplib模块实现FTP文件的上传下载

    python已经默认安装了ftplib模块,用其中的FTP类可以实现FTP文件的上传下载 FTP文件上传下载 # coding:utf8 from ftplib import FTP def uplo ...

  7. java之SFTP上传下载

    import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.ut ...

  8. java实操之使用jcraft进行sftp上传下载文件

    sftp作为临时的文件存储位置,在某些场合还是有其应景的,比如对账文件存放.需要提供一个上传的工具类.实现方法参考下: pom.xml中引入类库: <dependency> <gro ...

  9. SFTP上传下载(C#)

    sftp是ftp协议的升级版本,是牺牲上传速度为代价,换取安全性能,本人开始尝试使用Tamir.SharpSSH.dll但它对新版本的openssh 不支持,所有采用Ssh.Net方式 需要依赖:Re ...

随机推荐

  1. 《JAVA多线程编程核心技术》 笔记:第三章:线程间通信

    一. 等待/通知机制:wait()和notify()1.1.使用的原因:1.2 具体实现:wait()和notify()1.2.1 方法wait():1.2.2 方法notify():1.2.3 wa ...

  2. JS中:数组和二维数组、MAP、Set和枚举的使用

    1.数组和二维数组:   方法一: var names = ['Michael', 'Bob', 'Tracy']; names[0];// 'Michael' 方法二: var mycars=new ...

  3. python的三元运算

    python的三元运算是先输出结果,再判定条件.其格式如下: >>> def f(x,y): return x - y if x>y else abs(x-y) #如果x大于y ...

  4. 《挑战程序设计竞赛》2.3 动态规划-进阶 POJ1065 1631 3666 2392 2184(5)

    POJ1065: Description There is a pile of n wooden sticks. The length and weight of each stick are kno ...

  5. IOS And WCF 上传文件

    IOS And WCF Story 研究IOS上传到WCF图片的小功能,WCF实现服务端的文件上传的例子很多,单独实现IOS发送图片的例子也很多,但是两个结合起来的就很少了. 可以通过base64来上 ...

  6. mysql 中 select中 用case

    将 countertype 整数类型转成字符串类型 SELECT counterType, CASE counterType WHEN 1 THEN 'CTP'WHEN 2 THEN 'NULL'WH ...

  7. learnyou 相关网站

    http://learnyouahaskell.com/ http://learnyouahaskell-zh-tw.csie.org/ http://learnyousomeerlang.com/

  8. fun_action

    make an absolute URI from a relative one http://php.net/manual/en/function.header.php <?php /* Re ...

  9. wcf 开发 1

    1.创建wcf应用程序 2.生成服务,启动 3.使用工具生成 文件如下: 4.新增加winform程序项目,并添加文件 service1.cs 修改app.config 5.代码调用 private ...

  10. quartz集群 定时任务 改成可配置

    前面的博文中提到的quartz集群方式会有以下缺点: 1.假设配置了3个定时任务,job1,job2,job3,这时数据库里会有3条job相关的记录,如果下次上线要停掉一个定时任务job1,那即使定时 ...