设为首页 收藏本站
查看: 943|回复: 0

[经验分享] jdk7 FTP连接

[复制链接]

尚未签到

发表于 2016-6-8 02:14:54 | 显示全部楼层 |阅读模式
  使用jdk7用于连接和操作ftp服务器

package com.voiinnov.xingye.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpDirEntry;
import sun.net.ftp.FtpProtocolException;
public class FtpClientUtil {
private FtpClient ftpClient;   

public FtpClient getFtpClient(){
return this.ftpClient;
}
/**
* 连接FTP服务器
* @param ip  ip地址
* @param port 端口号
* @param user 用户名
* @param password  密码
* @param path  FTP的根目录
*/
public void connectServer(String ip, int port, String user, String password, String path) {
try {            
/* ******连接服务器的两种方法*******/            
ftpClient = FtpClient.create();            
try {               
SocketAddress addr = new InetSocketAddress(ip,port);
ftpClient.connect(addr);                 
ftpClient.login(user, password.toCharArray());
System.out.println("login success!");
//// 用2进制上传、下载
ftpClient.setBinaryType();
if (path!=null&&path.length() != 0){                        
//把远程系统上的目录切换到参数path所指定的目录                        
ftpClient.changeDirectory(path);
}            
} catch (FtpProtocolException e) {               
e.printStackTrace();            
}        
} catch (IOException ex) {            
ex.printStackTrace();            
}   
}  

/**     
* 关闭连接     
*/   
public void closeConnect() {        
try {            
ftpClient.close();            
System.out.println("disconnect success");        
} catch (IOException ex) {            
System.out.println("not disconnect");            
ex.printStackTrace();            
}   
}   
/**
* 上传文件使用流
* @param localFile
* @param remoteFile
*/
public void uploadStream(String localFile, String remoteFile){
FileInputStream is = null;
File file_in = new File(localFile);            
try {
is = new FileInputStream(file_in);
ftpClient.putFile(remoteFile, is);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (FtpProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**     
* 上传文件     
* @param localFile 本地文件     
* @param remoteFile 远程文件     
*/   
public void upload(String localFile, String remoteFile) {
//this.localfilename = localFile;        
//this.remotefilename = remoteFile;        
OutputStream os = null;        
FileInputStream is = null;        
try {            
//将远程文件加入输出流中            
try {               
os = ftpClient.putFileStream(remoteFile);            
} catch (
FtpProtocolException e) {               
e.printStackTrace();            
}            
//获取本地文件的输入流            
File file_in = new File(localFile);            
is = new FileInputStream(file_in);            
//创建一个缓冲区            
byte[] bytes = new byte[1024];            
int c;            
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);            
}            
System.out.println("upload success");        
} catch (IOException ex) {            
System.out.println("not upload");            
ex.printStackTrace();            
} finally{            
try {               
if(is != null){                    
is.close();               
}            
} catch (IOException e) {               
e.printStackTrace();            
} finally {               
try {                    
if(os != null){                        
os.close();                    
}               
} catch (IOException e) {                    
e.printStackTrace();               
}            
}        
}   
}  
/**     
* 下载文件     
* @param remoteFile 远程文件路径(服务器端)     
* @param localFile 本地文件路径(客户端)     
*/   
public void download(String remoteFile, String localFile) {        
InputStream is = null;        
FileOutputStream os = null;        
try {            
//获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。            
try {               
is = ftpClient.getFileStream(remoteFile);            
} catch (FtpProtocolException e) {                                
e.printStackTrace();            
}            
File file_in = new File(localFile);            
os = new FileOutputStream(file_in);            
byte[] bytes = new byte[1024];            
int c;            
while ((c = is.read(bytes)) != -1) {               
os.write(bytes, 0, c);            
}            
System.out.println("download success");        
} catch (IOException ex) {            
System.out.println("not download");            
ex.printStackTrace();            
} finally{            
try {               
if(is != null){                    
is.close();               
}            
} catch (IOException e) {               
e.printStackTrace();            
} finally {               
try {                    
if(os != null){                        
os.close();                    
}               
} catch (IOException e) {                    
e.printStackTrace();               
}            
}        
}   
}
/**
*
* @param remoteFile
* @return
*/
public String downFile2String(String remoteFile){
InputStream is = null;  
StringBuffer sb = null;
BufferedReader bufferReader = null;
try {
is = ftpClient.getFileStream(remoteFile);
sb = new StringBuffer();
bufferReader = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = bufferReader.readLine()) != null) {
System.out.println("读取的数据:"+line);
sb.append(line+"\n");
}
} catch (FtpProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
/**
* 判断FTP服务器已经连接并且登陆
* @return
*/
private  boolean  isConAndLogin(){
boolean flag = false;
flag =ftpClient.isLoggedIn()&&ftpClient.isConnected();
return flag ;
}
/**
* 创建目录
* @param path  目录名
* <br/>
* 如果需要一次性创建多个目录,可以使用这种字符串“test/test1/test2”直接创建多个目录
*/
public  void makeDir(String path){
try {
if(isConAndLogin()){
ftpClient.makeDirectory(path);
}else{
System.out.println("FTP没有连接成功");
}
} catch (FtpProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 重命名
* @param sPath  源文件名
* @param dPath  目标文件名
*/
public  void renameDir(String sPath , String dPath ){
try {
if(isConAndLogin()){
ftpClient.rename(sPath, dPath);
}else{
System.out.println("FTP没有连接成功");
}
} catch (FtpProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 递归删除文件夹
* @param path
*/
public void deleteDirs(String path) {
try {
Iterator<FtpDirEntry> dirEntryI =getFtpClient().listFiles(path);
if(dirEntryI.hasNext()){
FtpDirEntry entry = null;
while(dirEntryI.hasNext()){
entry = dirEntryI.next();
//System.out.println(entry.getType()+"    "+entry.getName());
if(entry.getType()==FtpDirEntry.Type.DIR){
this.deleteDirs(path+File.separator+entry.getName());
getFtpClient().removeDirectory(path+File.separator+entry.getName());
}else{
getFtpClient().deleteFile(path+File.separator+entry.getName());
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* 删除文件夹(删除的时候文件夹必须为空)
* @param path
*/
public  void delDir(String path){
try {
if(isConAndLogin()){
ftpClient.removeDirectory(path);
}else{
System.out.println("FTP没有连接成功");
}
} catch (FtpProtocolException e) {
System.out.println("没有连接");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 测试删除文件夹
*/
public static void testDleDir(){
FtpClientUtil fu = new FtpClientUtil();
/* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器         */  
fu.connectServer("127.0.0.1", 21, "test", "test", null);
String path = "20140512_back";
fu.deleteDirs(path);
fu.delDir(path);
fu.closeConnect();
}
/**
* 测试重命名文件夹
*/
public static void testRenameDir(){
FtpClientUtil fu = new FtpClientUtil();
/* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器         */  
fu.connectServer("127.0.0.1", 21, "test", "test", null);
String spath = "20150521";
String dpath = "20140512_back";
fu.renameDir(spath, dpath);
fu.closeConnect();
}

/**
* 测试单个文件上传
*/
public static void testSigleUplad(){
Date now = new Date();
SimpleDateFormat sDateFormat = new SimpleDateFormat();
sDateFormat.applyPattern("yyyyMMdd");
String dir = "/"+sDateFormat.format(now);
FtpClientUtil fu = new FtpClientUtil();
/* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器         */  
fu.connectServer("127.0.0.1", 21, "test", "test", null);
dir=dir+"/xingyeblank";
//在FTP创建文件夹
fu.makeDir(dir);
//本地文件
String localfile = "E:/test/ZXRZ_900201_TKSQ_20150521.txt";  
//上传到ftp远程文件
String remotefile = dir+"/ZXRZ_900201_TKSQ_20150521.txt";
//上传        
sDateFormat.applyPattern("yyyy-MM-dd   hh:mm:ss");   
System.out.println(sDateFormat.format(new java.util.Date()));// new Date()为获取当前系统时间        
fu.upload(localfile, remotefile);        
System.out.println(sDateFormat.format(new java.util.Date()));// new Date()为获取当前系统时间        
fu.closeConnect();   
}
/**
* 测试单个文件上传
*/
public static void testSigleUplad2(){
Date now = new Date();
SimpleDateFormat sDateFormat = new SimpleDateFormat();
sDateFormat.applyPattern("yyyyMMdd");
String dir = "/"+sDateFormat.format(now);
FtpClientUtil fu = new FtpClientUtil();
/* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器         */  
fu.connectServer("127.0.0.1", 21, "test", "test", null);
dir=dir+"/xingyeblank";
//在FTP创建文件夹
fu.makeDir(dir);
//本地文件
String localfile = "E:/test/ZXRZ_900201_TKSQ_20150521.txt";  
//上传到ftp远程文件
String remotefile = dir+"/ZXRZ_900201_TKSQ_20150521.txt";
//上传        
sDateFormat.applyPattern("yyyy-MM-dd   hh:mm:ss");   
System.out.println(sDateFormat.format(new java.util.Date()));// new Date()为获取当前系统时间        
fu.uploadStream(localfile, remotefile);  
System.out.println(sDateFormat.format(new java.util.Date()));// new Date()为获取当前系统时间        
fu.closeConnect();   
}
/**
* 测试文件加载
*/
public static void testDownFile(){
//下载到本地文件
String localfile = "E:/test/AESUtils副本3333.java";  
//ftp远程文件
String remotefile = "20150521/xingyeblank/AESUtils111.java";
FtpClientUtil fu = new FtpClientUtil();
/* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器         */  
fu.connectServer("127.0.0.1", 21, "test", "test", null);
fu.download(remotefile, localfile);
}
public static void testDownFile2String(){
//ftp远程文件
String remoteFile = "20150521/xingyeblank/ZXRZ_900201_TKSQ_20150521.txt";
FtpClientUtil fu = new FtpClientUtil();
/* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器         */  
fu.connectServer("127.0.0.1", 21, "test", "test", null);
String str = fu.downFile2String(remoteFile);
System.out.println(str);
}
/**
* 测试创建文件夹
*/
public static void testMakeDir(){
FtpClientUtil fu = new FtpClientUtil();
/* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器         */  
fu.connectServer("127.0.0.1", 21, "test", "test", null);
try {
fu.getFtpClient().makeDirectory("20150521/test");
fu.getFtpClient().makeDirectory("20150521/test2");
fu.getFtpClient().makeDirectory("20150521/test3");
fu.getFtpClient().makeDirectory("20150521/test4");
fu.getFtpClient().makeDirectory("20150521/test5");
fu.closeConnect();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String agrs[]) {  
//testSigleUplad();
//testMakeDir();
//testRenameDir();
//testDleDir();
//testDownFile();
//testDownFile2String();
testSigleUplad2();
//---------------其他方法的说明----------------
//从FTP下载指定的文件到OutputStream下
//ftpClient.getFile(String remotePath, OutputStream);
//如果是文件名列出文件信息,如果是目录则列出文件列表
//ftpClient.list(path);
//列出指定目录内容
//ftpClient.nameList(path);
}
}

  
  
  
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-227489-1-1.html 上篇帖子: 更改FTP登录密码 下篇帖子: 修改ftp上传路径
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表