java做的比较完善的FTP连接上传下载文件

本文介绍了一个用Java实现的FTP数据同步程序,该程序能够连接FTP服务器,并上传和下载文件。文章分享了完整的源代码,并提出了待解决的问题,包括如何删除已下载的文件、如何重命名上传的文件以及如何设置主动连接。
g&G%g# Y  java做的比较完善的FTP连接上传下载文件  
n<[Jo^H|Lf  
B+btNW  
~ 2&+Vmp 这 是偶第一次写java程序实现公司要求的FTP数据同步,所有原代码如下,以供各位参考并提出宝贵意见!另外俺还有两个功能没有实现,有请高手指点一二: 1、如何删除FTP服务器上已经下载过的文件?2、如何将上传的文件改名?上传时在文件名前加“temp_”,上传完毕后需要把文件名改回来。3、如何使 用openPassiveDataConnection()方法将ftp连接更改为主动连接,因为要从unix系统配置的ftp服务器下载文件的话,就需 要主动连接。 
h6h<(.2  
n76go2n  
f P:5(e,  
6xq1p>1mi /* 
E+8>z>< ******************************************************************************************************* 
NYUI+iktW  
` ce~# Filename: ftp.java 
&=]o*'CW Author:   leetsing(elove) 
hizkElY Create date: 2004-08-30 
Y+m,u& e Use:   connect to FTP server,then upload and download file 
<c}EE{&w Modify date: 2004-09-05 add to upload file 
1Frkb5>s   2004-09-13 add to download file 
:b#g,|/ 6 Copy right: Magisky Media Technology Co.,Ltd. 
!XjVDP  
Y|f9`7U ******************************************************************************************************* 
+uAk:/~ */ 
`-rl9 //import cz.dhl.io.*; 
fXxV5D8"f //import cz.dhl.ftp.*; 
TtORsu/"7 import sun.net.ftp.*;  
SY Kl/+c^ import sun.net.*; 
K;~rkZ P import java.applet.*;  
{x]1Bq v import java.io.*; 
@xF6e0`m import java.io.IOException; 
<*QG-uj import java.util.StringTokenizer; 
naYEEr _GH import sun.net.ftp.FtpClient; 
]Oh8gFkv import java.util.ArrayList; 
@Z+ Zs@"$  
sfS@~RzYJ/ public class ftp extends Applet 
I>0L@rx
#xfD? d FtpClient aftp;  
}`& AY]]K DataOutputStream outputs ;  
]-ZcATn$ TelnetInputStream ins;  
mHZ(u^R TelnetOutputStream outs; 
"^0keq<  
BZ Hq_^# int ch;  
j(W|$gH# public String a;  
8 ,'G>) f String hostname=""; 
r(^~IHT2F private String path = "/"; 
.fr.})d1  
c yi?dq-V public static void main(String[] args)  
cLy'~$U
.XNE$W_ String hostname = "192.168.0.56"; 
)9RN int port = 2121; 
Io/7*)d} String uid = "lee"; 
TfbEZrD&H String pwd = "lee"; 
GB[=x'MxE String RWFileDir = "D:/smsftp/";//文件目录 
@.FSfg5  
XdX|z6QYf //连接ftp服务器 
ZKZaw^xT ftp ft = new ftp(); 
Q+A?sdc^Y% ft.connect(RWFileDir,hostname,port,uid,pwd);  
Tn?r*gk#  
Qa45s[w //下载文件 
dQ4!tZg if (ft.aftp != null){ 
9mvHrS]   try { 
K7cQxe!   ft.getNameList(RWFileDir); 
^:'Sc(   }catch(IOException e)  
K$R0?H~N   {  
v=7cIyY   System.out.println("下载文件出错:"+e); 
RwT^1   }  
A?snb#2~
Nn7(+<  
+| ~&^YC  
"a$%6=aSXK //上传文件 
IL=!R}N; if (ft.aftp != null){ 
STx&OISh   String sdir = RWFileDir + "subunsubfromsp/"; 
SO>e|Md   File fdir = new File(sdir); 
6Y1[d>)V   String FileName = ""; 
#u%vWpt{z  
  for(int i=0;i   FileName = sdir + (fdir.list()) h7j.@P
  LMTcLn`  
  ft.uploadFile(RWFileDir,FileName); g] ,rW  
  } #` YYa  
  //System.out.println("成功上传的文件:"); RUU+o+}"N  
  //ft.showFileContents("subunsubfromsp/"); N'3vz]&'  
} t$;orwOy  
+{%@6Rcb  
//删除subunsubfromsp目录下已经上传的文件文件 FLmj5*  
// ft.deleFile(RWFileDir); 2z2{k y  
nQ[&Z.  
//断开服务器连接 dEu eXE?  
ft.stop(RWFileDir); |<]M3*7  
Os*{X9k  
} PaQx*rRi:  
vS-/b!  
public FtpClient connect(String RWFileDir,String hostname,int port,String uid,String pwd) FrP<"S;Xz  
{ dOQ1E )49  
this.hostname = hostname; hX WZI6o%l  
System.out.println("正在连接"+hostname+",请等待....."); K 9 L|K  
try{ s>iVz/Z  
  aftp = new FtpClient(hostname,port); va3*1v  
  aftp.login(uid,pwd); B xqfvbgj  
  aftp.binary(); 'E^<#rTW}  
  //aftp.openPortDataConnection(); kaQZ2)  
  a = "连接主机:"+hostname+"成功!"; *Fo7i9=L  
  System.out.println(a); -C$FfR  
} :vZ:hM**Vb  
catch(FtpLoginException e){ MM0%(bM=  
  a="登陆主机:"+hostname+"失败!请检查用户名或密码是否正确:"+e; SOIQ3Kj  
  System.out.println(a); 3 InnHb  
  //return false; d[O ^rq[  
} oxCiP1  
catch (IOException e){ X7iz+a4  
  a="连接主机:"+hostname+"失败!请检查端口是否正确:"+e; %K^pNs;  
  System.out.println(a); >7!D LlJ  
  //return false; R/lL]|Xj  
} y[b[oaIohn  
catch(SecurityException e) F|2 JC6]T  
{ .N0PT  
  a="无权限与主机:"+hostname+"连接!请检查是否有访问权限:"+e; l{V5h|Z  
  System.out.println(a); <!JCt  
  //return false; juzzi%[C  
} 5 ?%P=!  
^lVXgq  
log(RWFileDir,a); 8 $qe(Y  
return aftp; 0;d fmW.  
} 9?~(tS  
GSQ% |  
public void stop(String RWFileDir) Ik'S':  
{ - ]^|h)Y  
String message = ""; hf-Dj%N  
try { G;""/Sq  
  if(aftp!=null){ Qp bh[ ;:  
  aftp.closeServer(); -" Ofc:]18  
  message = "与主机"+hostname+"连接已断开!"; G'Zjb}  
  System.out.println(message); c6[]R0n}  
  log(RWFileDir,message); ^G< 8%*  
  } }qT*RNs  
} A156XkrR  
catch(IOException e) iwG' *B{  
{ N.y }Q  
  message = "与主机"+hostname+"断开连接失败!"+e; Hz_Bym~e  
  System.out.println(message); ~AJZBi"  
  log(RWFileDir,message); ^U?D+e Y  
} ,:8oZJP>o  
} >ywFcYd-  
F `- L  
?N$- Wa  
public boolean downloadFile(String RWFileDir,String filepathname){ Q#Bcdi  
boolean result=true; Y[g.o[{55"  
String message = ""; +v0wfbt#|  
if (aftp != null) @ lc xgT  
{ %((QV**  
  System.out.println("正在下载文件"+filepathname+",请等待...."); fTB~6|NR  
  String badfile = filepathname.substring(filepathname.length()-4,filepathname.length()); #7AGA'g}  
  String badlog = filepathname.substring(filepathname.length()-7,filepathname.length()); }Zhk:(+gT  
  String baddir = ""; E(e5a$@z  
  if ((badfile.compareTo(".bad") != 0) && (badlog.compareTo(".badlog") != 0)){ u F$?WD;  
  baddir = "subunsubtosp/"; _glx>t6  
  } ks(U #e  
  else{ :u(7y8 [O  
  baddir = "bad/"; tI[!-f9  
  } E=-^N.R  
  String strdir = "subunsubtosp/"; Hy rg$t E  
  //System.out.println(RWFileDir + baddir + filepathname); %)}Y4 _  
  try{ Zq@hqDBY(  
  //FtpClient fc=new FtpClient("192.168.0.56",2121); OFx8+?yR  
  //fc.login("lee","lee"); ;1M  
  int ch; P  
  File fi = new File(RWFileDir + baddir + filepathname); * kwC<E_e  
  //aftp.cd(strdir); ];g .)`  
  RandomAccessFile getFile = new RandomAccessFile(fi,"rw"); O9Im1  
  getFile.seek(0); b=8]H08L%  
  TelnetInputStream fget=aftp.get(strdir+filepathname); Ph[{I?ZtZ  
  DataInputStream puts = new DataInputStream(fget); Wr oltd  
  while ((ch = puts.read()) >= 0) { &h ; `qb  
  getFile.write(ch); J">hi`y%W  
  ka9XeD(B  
  } NaPlOw>  
  //s.delete(); xK]Q0+ ^P  
  ~KgoT"F  
  fget.close(); vI{ Lzn.  
  getFile.close(); @8^Y_ce  
  //fc.closeServer(); n^>5c'$y  
q&_+AuO  
  message = "下载"+filepathname+"文件到"+baddir +"目录成功!"; 4<VxVu "4  
  System.out.println(message); W_B%9k7i  
  log(RWFileDir,message); ktwi|1t  
  } &f>b~B#g  
  catch(IOException e){ 7;4b<nF  
  message = "下载"+filepathname+"文件到"+baddir +"目录失败!"+e; bET]V'{  
  System.out.println(message); ahuYOL!v  
  log(RWFileDir,message); =tC7cK:  
  result = false ; 2FS;vgo_  
/"Mt*~Y  
  } [[iI`@#  
} a::IivT k  
else{ O/9{UED|A  
  result = false; [Dw]<Le  
} &* uL9Q,L  
return result; ~BPvD$l  
} 23F03TW92  
rW )oPYX  
98 K Rr>  
public boolean uploadFile(String RWFileDir,String filepathname){ [/D#K`'#  
boolean result=true; !IWS[mL9e  
String message = ""; }9]"O4 #k  
if (aftp != null) P [@{.  
{ .aEJ8@  
  System.out.println("正在上传文件"+filepathname+",请等待...."); 19/ joh  
65Ujb0  
  try{ ?UXr]Ey0  
  String fg =new String("/subunsubfromsp/"); ;j%9(IMK  
  int index = filepathname.lastIndexOf(fg); DxRh}rn&9  
  String filename = filepathname.substring(index+1); '&8J j  
  File localFile = new File(filepathname) ; ^o`#"~-  
    SPs"~)T  
  RandomAccessFile sendFile = new RandomAccessFile(filepathname,"r"); '<lXfe%M&  
  // EgGv z;r  
  sendFile.seek(0); gc]x3re,  
  //改名上传temp_ (=3%A8U|  
  filename = filename.substring(0,15)+"temp_"+filename.substring(15,filename.length()); #]F|>#2V  
  outs = aftp.put(filename); %8 tGDH< #  
  outputs = new DataOutputStream(outs); ?Q9r 7 Wv  
  while (sendFile.getFilePointer() < sendFile.length() ) vofwA|US  
  { k_J-iG  
  ch = sendFile.read(); N0MpTHPx  
  outputs.write(ch); 8 VZ<T_i  
  } )H}u  
  B0:u>U5t  
  rename(filename.substring(15,filename.length()),filename.substring(20,filename.length())); I3~9~ 'bn  
  outs.close(); IJddHf-  
  sendFile.close(); eJb}"s  
  rP53 zN  
  message = "上传"+filepathname+"文件成功!"; W/qs@dR_  
  System.out.println(message); oi&o&V  
  log(RWFileDir,message); ](kv' T  
  } 3z,hP/  
  catch(IOException e){ _a otT  
  message = "上传"+filepathname+"文件失败!"+e; I8Hd{EtKB  
  System.out.println(message); y@ I8e'J  
  log(RWFileDir,message); 8< G//O  
  result = false ; KcJMX  
ow#NeWVt  
  } ^%8bsa"p  
} 6/kW T vD  
else{ cS n>A3O  
  result = false; KeLd9T  
} <U?@|?  
return result; af?Qh ^  
} _{K7>4.8t  
-Fp.uq  
public void rename(String oldName,String newName){ .<mEBAH  
_Vf#)v]Fo  
  //aftp.renameTo(oldName,newName); E}WGn  
  File Old = new File(oldName); //oldName Q3,Sq)u*  
  File New = new File(newName); //newName UUz3<tvSV  
  //aftp.renameTo(New); 6N)/hqi"k  
  //boolean Old.renameTo(File newName); vH`J|{kD  
  //System.out.println(Old); tn>|R.  
  //System.out.println(New); 8 /G,, 4E  
d& }oc  
} nvgiKCy]  
(Q yK/  
public static void deleFile(String RWFileDir) { 6|odqQ  
//try { ,Xjb+Nn()h  
//取得ReadFile目录下的txt文件 i}) ]b3 `  
String sdir = RWFileDir + "subunsubfromsp/"; B> !KVSO  
File fdir = new File(sdir); rxx}NFztE  
String FileName = ""; WU4Tg:h  
int j = fdir.list().length; b<BXn>&6  
<Y5_-QG&|  
System.out.println(sdir+"目录下要删除的文件数:"+fdir.list().length); 1b$k+ysQw  
File file; "-Ipp W-f  
for(int i=0;i { w&6JepE&6  
  //删除subunsubfromsp中的txt文件 Lz5zBBK  
  FileName = RWFileDir + "subunsubfromsp/" + (fdir.list())[0]; o-i1u;*R  
  file = new File(FileName); k;B N/1.7`  
  file.delete(); f!['<V  
  System.out.println("已经成功删除"+FileName+"文件!"); 6~KjZ<  
} U~M fSmZd  
//} z? 6Ez!|  
//catch (IOException e) { JTMP2OL^,  
// System.out.println("删除txt文件错误!"); QX/0r c BH  
// e.printStackTrace(); OFje<S"$E7  
//} 0&_N-%]$EU  
} P~F3K{.1  
]a5rLV@1mu  
^e62"O  
public void showFileContents(String strdir) *8qhdi7)~  
{ 5+U</  
StringBuffer buf = new StringBuffer(); o8(T*N(E1  
try { f[V/?Y  
  aftp.cd(strdir); nY>a(&z  
  ins= aftp.list(); F%T a}  
  while ((ch=ins.read())>=0){ jz SR(*-  
  buf.append((char)ch); q[VXEb  
  } ,Zf5qz(@  
  0<ZZIi:  
  System.out.println(buf.toString()); x]a/+"0h  
P4$z=p_C  
  ins.close(); {y nBC  
    } 3.GJH#xZ  
catch(IOException e) 'Lb0'UtI  
{ 3;-Z~8 Ji  
} RgD++q  
} M`^FQ  
gJI&%n,z  
pMQW!m:V  
b:)kDTx  
// 返回当前目录的所有文件及文件夹 =8vS9]g 0  
!S(UBs  
public ArrayList getFileList() throws IOException { 2a_~<q63nD  
BufferedReader dr = new BufferedReader(new InputStreamReader(aftp.list())); mKz6,KRH  
ArrayList al = new ArrayList(); rF$Nr  
String s = ""; S32!<U{*K  
while ( (s = dr.readLine()) != null) { P_VDv/|c  
al.add(s); 75pe7$- Z-  
} )QswUPJ]  
return al; I{FdfRDQE  
} #a{z`>I^  
/ >W$  
public void setPath(String path) throws IOException { iKo0bo{  
if (aftp == null) I#.tQY  
this.path = path; 6~F 0>u;  
else { ^ft0hl!6  
  aftp.cd(path); ,{-=izB  
} K}=u8h6b  
} I9}in 9  
BMo#gzd~=  
// 返回当前目录的文件名称 Te^EJ@|  
oI5.,]h>A?  
public ArrayList getNameList(String RWFileDir) throws IOException { ]O;V4P;L  
2hP::gibz  
BufferedReader dr = new BufferedReader(new InputStreamReader(aftp.nameList("subunsubtosp/"))); 9`E+>l^'/5  
ArrayList al = new ArrayList(); `-Qcu  
String s = ""; JA}$PtGG  
while ( (s = dr.readLine()) != null) { T}sjR%NC  
  al.add(s); comK30{  
  s = s.substring(13,s.length()); "Kr-`'E  
  isFile(s); Y|Z*i#  
  downloadFile(RWFileDir,s); ;MCCd.$bo  
  //String strFileDelF = aftp.nameList("subunsubtosp/"); -xbc:Yo  
  File fileDelF=new File(s); S!SOYJ/  
  fileDelF.delete(); =M2S'uo  
} a/=N&}*`(q  
return al; J,RQjUW-  
//System.out.println(al.add(s)); d07 VK  
} ]e,_ Sz  
-]Fuf9gZR@  
// 判断一行文件信息是否为目录 eg SlS  
g:Sgt ll  
public boolean isDir(String line) { P4+"n.dO(  
return ( (String) parseLine(line).get(0)).indexOf("d") != -1; QO> mo.B  
} z>m/6*8f  
,:^4g)zeqF  
public boolean isFile(String line) { F+~ITtLC]  
return!isDir(line); U h,o)-iR  
} APVX  
2X S/  
// 处理getFileList取得的行信息 n %{ hS Rx  
CX=G.bp  
private ArrayList parseLine(String line) { xz+o(37  
ArrayList s1 = new ArrayList(); i}R0I1zS  
StringTokenizer st = new StringTokenizer(line, " "); ?gLwz  
while (st.hasMoreTokens()) { u =O~P  
  s1.add(st.nextToken()); ;Rzx9h2  
} cLx3h  
  return s1; !g7^CA7$n  
} rjgU1  
/S?l _t9  
//写消息日志 -# S:R/  
public static void log(String RWFileDir,String msg) V/6=H'T  
{ q"SUl 3  
String message = ""; ?m*`!= 8  
try { dtk.pz<y  
  java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 8B+W)JZR  
  java.text.DateFormat dflog = new java.text.SimpleDateFormat("yyyyMMdd"); kY: _jV  
  java.util.Date date = new java.util.Date() ; am0#T,ab;  
  String datestr = df.format(new java.util.Date()) ; n^<_ m{  
  String datelog = dflog.format(new java.util.Date()) ; .~4bnRK  
  //String datelog = datestr.substring(0,10); UHi!>J'  
  //datelog = datelog.replace('-',' '); xDg11@G  
3<l5c}"q  
  //按日期每天生成一个日志文件 /v9o1x  
  FileWriter fwl = new FileWriter(RWFileDir + "CMSSftp"+datelog+".log",true); ']{K6y h  
  PrintWriter outl = new PrintWriter(fwl); _a3P7D_D  
  outl.println(datestr + " " + msg); w]"Z2Yl)XK  
  outl.close(); ]xI,,FBJO{  
  fwl.close(); eMp*h4  
}catch (IOException e) { 5!f|bS]Y  
  message = "写log文件错误!"+e; G_n 4?/u  
  e.printStackTrace(); 2fM^+Y<*  
  log(RWFileDir,message); +s. ]bE@  
  System.out.println(message); AJ6'O/  
} P~ 7H@e  
} _ y' MEuJ  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值