连接ftp服务器 JDK 1.7
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import org.apache.log4j.Logger; import com.zhiwei.core.util.AppUtil; import java.net.InetSocketAddress; import java.net.SocketAddress; import sun.net.TelnetInputStream; import sun.net.TelnetOutputStream; import sun.net.ftp.FtpClient; import sun.net.ftp.FtpProtocolException; public class FtpUtils { protected static Logger LOG=Logger.getLogger(FtpUtils.class); private FtpClient ftpClient=null; /** * 连接ftp服务器 JDK 1.7 * * @param url * @param port * @param username * @param password * @return FtpClient * @throws FtpProtocolException * @throws IOException */ public FtpClient connect(String url, int port, String username, String password) { // 创建ftp try { // 创建地址 SocketAddress addr = new InetSocketAddress(url, port); // 连接 ftpClient = FtpClient.create(); ftpClient.setConnectTimeout(6000000); ftpClient.connect(addr); // 登陆 ftpClient.login(username, password.toCharArray()); ftpClient.setBinaryType(); System.out.println("------------------------------ftp服务器已连接----------------------"); } catch (FtpProtocolException e) { LOG.error("ftp连接服务器出错,出错原因\r\n", e); } catch (IOException e) { LOG.error("ftp连接服务器出错,出错原因", e); } return ftpClient; } /** * 切换目录 * * @param ftp * @param path */ public void cd(String path) { try { ftpClient.changeDirectory(path); LOG.info("切换目录"+ftpClient.getWorkingDirectory()); // System.out.println(ftpClient.getWorkingDirectory()); } catch (FtpProtocolException e) { LOG.error("切换目录出错",e); } catch (IOException e) { LOG.error("切换目录出错",e); } } //上传创建的文件夹或文件 public void uploadDirectory(String directory,boolean bl,String nameFtp,String n,String serverIp,String username,String password)throws IOException, FtpProtocolException{ if (ftpClient==null) { Integer ss = Integer.valueOf(n); connect(serverIp, ss,username , password); } File file=new File(directory); String name=null;//待上传文件名 boolean result; if(file.isDirectory()){ String dir = file.getName(); if(bl){ dir = nameFtp; bl = false; } result=isDirExist(ftpClient,dir); if (!result) { LOG.error(dir+"----------该文件夹已存在"); } try { ftpClient.changeDirectory(dir); ftpClient.setBinaryType(); } catch (FtpProtocolException e) { LOG.error("------进入"+dir+"文件夹失败--------",e); } String[] files = file.list(); for (int i = 0; i < files.length; i++) { File tmpFile = new File(file.getPath()+"\\"+files[i] ); if(tmpFile.isDirectory()){ uploadDirectory(tmpFile.getAbsolutePath(),bl,nameFtp, n, serverIp, username, password); }else{ name=tmpFile.getName(); upload(directory+"/"+name, n, serverIp, username, password); } } ftpClient.changeToParentDirectory(); }else{ //文件上传 upload(directory,file.getName(), n, serverIp, username, password); } } //文件上传 public void upload(String srcFile,String n,String serverIp,String username,String password)throws IOException{ File file=new File(srcFile); FileInputStream fin=new FileInputStream(srcFile); TelnetOutputStream tos = null; try { tos = (TelnetOutputStream) ftpClient.putFileStream(file.getName(), true); if(file.getName().equals("spring.xml")){ InputStreamReader ie=new InputStreamReader(fin, "utf-8"); BufferedReader reader = new BufferedReader(ie); String line = null; while ((line = reader.readLine()) != null) { if(line.indexOf("serverIp")!=-1){ line=line.replaceAll("serverIp", serverIp); line=line.replaceAll("dataName", n); } if(line.indexOf("datausername")!=-1){ line=line.replaceAll("datausername", username); } if(line.indexOf("datapassword")!=-1){ line=line.replaceAll("datapassword", password); } tos.write(line.getBytes("utf-8")); } reader.close(); ie.close(); }else{ int readLength = 0; byte[] buf = new byte[1024]; while ( (readLength = fin.read(buf)) != -1) { tos.write(buf, 0, readLength); } } fin.close(); tos.close(); } catch (Exception e) { //System.out.println("--------获取远程文件输出流失败---"); LOG.error("--------获取远程文件输出流失败---",e ); } } public void upload(String srcFile,String destFile,String n,String serverIp,String username,String password)throws IOException{ upload(srcFile, n, serverIp, username, password); File file=new File(srcFile); //文件重命名 打开 上传 zip文件会报错 先关闭 // ftpClient.rename(file.getName(), destFile); } public void close(){ try { ftpClient.close(); } catch (IOException e) { LOG.error("关闭输出流失败",e); } } /** * @param directory 上传文件在服务器上的存放路径 * @param srcFilePath 要上传文件的存放路径 * svn:songwj * 创建文件夹、调用上传方法进行上传 * @throws FtpProtocolException */ public void swjUploadDirectory(String directory,String srcFilePath,boolean bl,String nameFtp,String n,String serverIp,String username,String password,String dirStr)throws IOException, FtpProtocolException{ System.out.println("服务器上要创建文件夹路径-------------"+dirStr); boolean result; //1 创建各个节点的文件夹 if(!"".equals(dirStr)){ String dir =dirStr; String url[] = dir.split("/"); for(int i = 0;i<url.length;i++){ try { result=isDirExist(ftpClient,url[i]); if (result) { LOG.info("创建"+url[i]+"成功"); }else { LOG.info(url[i]+"已存在"); } ftpClient.changeDirectory(url[i]); ftpClient.setBinaryType(); } catch (FtpProtocolException e) { LOG.error("------创建文件夹失败-----", e); } } } //2 调用上传方法上传文件 swjUpload(srcFilePath,directory, n, serverIp, username, password); } /** 判断Ftp目录是否存在 * @throws FtpProtocolException */ public boolean isDirExist(FtpClient ftpClient, String dir) { try{ ftpClient.makeDirectory(dir); } catch (FtpProtocolException e1){ return false; }catch (IOException e) { return false; } return true; } /** * 文件上传代码 * @param srcFile 要上传文件的路径 * @param fileToServerPath 上传文件存放在服务器上的位置 * @param n * @param serverIp * @param username * @param password * @throws IOException */ public void swjUpload(String srcFile,String fileToServerPath,String n,String serverIp,String username,String password)throws IOException{ //创建一个文件(服务器上对应的文件) File serverFile = new File(fileToServerPath); //创建选择要上传的文件对象 File srFile=new File(srcFile); //把上传的文件对象放入文件流中 FileInputStream fin=new FileInputStream(srcFile); LOG.info("上传到服务器地址==="+fileToServerPath); //System.out.println("fileToServerPath==="+fileToServerPath); //打开ftp上的文件 准备接收 TelnetOutputStream tos = null; try { tos = (TelnetOutputStream) ftpClient.putFileStream(serverFile.getName(), true); if(srFile.getName().equals("spring.xml")){ InputStreamReader ie=new InputStreamReader(fin, "utf-8"); BufferedReader reader = new BufferedReader(ie);//读取要上传的 文件 String line = null; while ((line = reader.readLine()) != null) { if(line.indexOf("serverIp")!=-1){ line=line.replaceAll("serverIp", serverIp); line=line.replaceAll("dataName", n); } if(line.indexOf("datausername")!=-1){ line=line.replaceAll("datausername", username); } if(line.indexOf("datapassword")!=-1){ line=line.replaceAll("datapassword", password); } tos.write(line.getBytes("utf-8")); } reader.close(); ie.close(); }else{ int readLength = 0; byte[] buf = new byte[1024]; while ( (readLength = fin.read(buf)) != -1) { tos.write(buf, 0, readLength);//把要上传文件流写入服务器的文件中 } } tos.close(); } catch (Exception e) { LOG.error("上传文件到服务器失败", e); } fin.close(); } /** * Ftp 服务器文件下载单个文件 * svn:songwj * @param srcStr 要下载文件的路径 * @param disStr 下载文件存放的路径 */ public void ftpDownFile(String srcStr,String disStr) { // 读取配置文件读取ftp ip地址 端口号 账户 密码 String ip = AppUtil.getFtpIp(); String us = AppUtil.getFtpUsName();//帐号 String ps = AppUtil.getFtpPss();//密码 int port = Integer.valueOf(AppUtil.getFtpPort());//端口 默认为 21 connect(ip, port, us, ps); TelnetInputStream is = null; FileOutputStream os = null; System.out.println("srcStr--------------------"+srcStr); System.out.println("disStr--------------------"+disStr); try { //获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。 ftpClient.changeDirectory(srcStr); is = (TelnetInputStream) ftpClient.getFileStream(srcStr); System.out.println("os--------------------"+os.toString()); byte[] bytes = new byte[2048]; int c; while ((c = is.read(bytes)) != -1) { os.write(bytes, 0, c); } System.out.println("----------------下载成功----------------"); } catch (IOException ex) { //System.out.println("下载失败"); LOG.error("---------------下载失败--------------", ex); throw new RuntimeException(ex); } catch (FtpProtocolException e) { LOG.error("----------------下载失败----------------", e); } finally{ try { if(is != null){ is.close(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if(os != null){ os.close(); } } catch (IOException e) { e.printStackTrace(); } } } } /** * 删除ftp服务器上指定的文件 * @param fileName */ public String removeFile(String deleteFilePath){ System.out.println("---------进入到删除方法中"); String resultStr = ""; if(ftpClient!= null){ try { ftpClient.deleteFile(deleteFilePath); //ftpClient.deleteFile("D:/sendMessagePicture.png"); //ftpClient.deleteFile( "D:\\sendMessagePicture.png"); resultStr = ftpClient.getLastResponseString(); //FtpReplyCode lastReplyCode = ftpClient.getLastReplyCode(); System.out.println("status----------------"+resultStr); } catch (Exception e) { LOG.error("删除失败", e); } }else{ resultStr = "FAIL"; } return resultStr; } } |
连接ftp服务器 JDK 1.7的更多相关文章
- 【FTP】C# System.Net.FtpClient库连接ftp服务器(上传文件)
如果自己单枪匹马写一个连接ftp服务器代码那是相当恐怖的(socket通信),有一个评价较高的dll库可以供我们使用. 那就是System.Net.FtpClient,链接地址:https://net ...
- 【FTP】C# System.Net.FtpClient库连接ftp服务器(下载文件)
如果自己单枪匹马写一个连接ftp服务器代码那是相当恐怖的(socket通信),有一个评价较高的dll库可以供我们使用. 那就是System.Net.FtpClient,链接地址:https://net ...
- java 无法连接ftp服务器(500 OOPS: cannot change directory)
在使用java连接ftp服务器时可能会出现无法连接的情况,检查代码是没有错误的,这时就应该考虑一下服务器端的情况了: 首先用在本地打开命令窗口,输入:ftp ftp服务器IP,窗口会提示你输入用户名密 ...
- linux下常用FTP命令 1. 连接ftp服务器
1. 连接ftp服务器 格式:ftp [hostname| ip-address] a)在linux命令行下输入: ftp 192.168.1.1 b)服务器询问你用户名和密码,分别输入用户名和相应密 ...
- linux下常用FTP命令 1. 连接ftp服务器[转]
1. 连接ftp服务器 格式:ftp [hostname| ip-address]a)在linux命令行下输入: ftp 192.168.1.1 b)服务器询问你用户名和密码,分别输入用户名和相应密码 ...
- 【VS2019】Web项目发布时提示无法连接FTP服务器
使用 Visual Studio 2019 时出现的问题 环境:win10 ltsc 场景 发布Web项目到FTP时 失败,并提示 _无法打开网站"ftp://...".未安装与 ...
- MFC连接ftp服务器
CInternetSession* m_pInetSession; CFtpConnection* m_pFtpConnection; //连接服务器的函数 BOOL CftpClientDlg: ...
- 常用FTP命令 1. 连接ftp服务器
1. 连接ftp服务器 格式:ftp [hostname| ip-address]a)在linux命令行下输入: ftp 192.168.1.1 b)服务器询问你用户名和密码,分别输入用户名和相应密码 ...
- 通过JAVA对FTP服务器连接,上传,下载,读取,移动文件等
记录一次对FTP服务器文件内容 通过Java程序对FTP服务器文件处理:连接,上传,下载,读取,移动文件等. 需求描述:今天接到一个任务,在Java项目中,读取FTP服务器上的一些文件,进行一些业务操 ...
随机推荐
- Ubuntu 14.04更新为国内阿里源解决apt-get install无法执行的问题
step01: sudo gedit /etc/apt/sources.list #将下面全部粘贴到sources.list中deb http://mirrors.aliyun.com/ubuntu/ ...
- scrum-master个人实践回顾总结
个人回顾总结 一.开课提出问题 第一次博客地址:https://www.cnblogs.com/Slow-Walker/p/11513179.html 二.问题回答 2.1问题1:针对单元测试 怎么保 ...
- mysql毫秒数引发的问题
起因:最近同事在做定时打卡的东西,遇到一个诡异的问题,端只是传了一个开始时间跟打卡周期,剩下的打卡时间都是由服务端自己生成的,显示的截止时间有的变成==23:59:59==. 有时候又变成了 ==00 ...
- 微信之通过AppID和AppSecret获取access_token
最近在搞微信公众平台这方面的东西,,但实际使用的时候发现和access_token有关的接口都无法正常调用,于是debug了下,发现获取到了AppID和AppSecret,在最后请求access_to ...
- 201671010417 金振兴 实验十四 团队项目评审&课程学习总结
项目 内容 软件工程 https://www.cnblogs.com/nwnu-daizh/ 作业要求 https://www.cnblogs.com/sunmiaokun/p/11095027.ht ...
- 牛客NOIP暑期七天营-提高组5
A:deco的abs. 水题,先%,然后相邻两个数min()一下差值. #include<bits/stdc++.h> #define ll long long using namespa ...
- js回调与异步加载的用法
以前还是菜鸟的时候(虽然现在依然很菜 -_-|| )对异步加载与回调函数的技术无比向往,但也一直没有使用过,这次因为页面逻辑太过复杂,一堆请求逻辑,如果还是用顺序请求,页面的速度... 领导又要挠头了 ...
- 使用Map文件查找崩溃信息
简介 编写整洁的应用程序是一回事.但是当用户告诉你你的软件已经崩溃时,你知道在添加其他功能之前最好先解决这个问题.如果你够幸运的话,用户会有一个崩溃地址.这将大大有助于解决这个问题.但是你怎么能用这个 ...
- Xamarin NuGet 缓存包导致 already added : Landroid/support/annotation/AnimRes 问题解决方案
在VS中打开您遇到问题的解决方案. 转到工具> NuGet包管理器>包管理器设置 - >常规,然后点击“清除所有NuGet缓存” 这应该返回一个错误,因为你有一个项目打开,但如果没有 ...
- [RN] React Native 删除第三方开源组件依赖包 后 还要做的 (以 删除 react-native-video为例)
近期测试使用了下 react-native-video 使用一直不成功,后来想着删除掉, 使用命令: npm uninstall react-native-video 重新编译后,还是一直报错 后来 ...