服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

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


这是偶第一次写java程序实现公司要求的ftp数据同步,所有原代码如下,以供各位参考并提出宝贵意见!另外俺还有两个功能没有实现,有请高手指点一二:1、如何删除ftp服务器上已经下载过的文件?2、如何将上传的文件改名?上传时在文件名前加“temp_”,上传完毕后需要把文件名改回来。3、如何使用openpassivedataconnection()方法将ftp连接更改为主动连接,因为要从unix系统配置的ftp服务器下载文件的话,就需要主动连接。



/*
*******************************************************************************************************

filename:  ftp.java
author:   leetsing(elove)
create date: 2004-08-30
use:   connect to ftp server,then upload and download file
modify date: 2004-09-05 add to upload file
     2004-09-13 add to download file
copy right:  magisky media technology co.,ltd.

*******************************************************************************************************
*/
//import cz.dhl.io.*;
//import cz.dhl.ftp.*;
import sun.net.ftp.*;
import sun.net.*;
import java.applet.*;
import java.io.*;
import java.io.ioexception;
import java.util.stringtokenizer;
import sun.net.ftp.ftpclient;
import java.util.arraylist;

public class ftp  extends applet
{
ftpclient aftp;
dataoutputstream outputs ;
telnetinputstream ins;
telnetoutputstream outs;

int ch;
public string a;
string hostname="";
private string path = "/";

public static void main(string[] args)
{
  string hostname = "192.168.0.56";
  int port = 2121;
  string uid = "lee";
  string pwd = "lee";
  string rwfiledir = "d://smsftp//";//文件目录

  //连接ftp服务器
  ftp ft = new  ftp();
  ft.connect(rwfiledir,hostname,port,uid,pwd);

  //下载文件
  if (ft.aftp != null){
   try {
    ft.getnamelist(rwfiledir);
   }catch(ioexception e)
   {
    system.out.println("下载文件出错:"+e);
   }
  }


  //上传文件
  if (ft.aftp != null){
   string sdir = rwfiledir + "subunsubfromsp//";
   file fdir = new file(sdir);
   string filename = "";
  
   for(int i=0;i    filename = sdir + (fdir.list())[i];
   
    ft.uploadfile(rwfiledir,filename);
   }
   //system.out.println("成功上传的文件:");
   //ft.showfilecontents("subunsubfromsp//");
  }

  //删除subunsubfromsp目录下已经上传的文件文件
//  ft.delefile(rwfiledir);

  //断开服务器连接
  ft.stop(rwfiledir);

}

public ftpclient connect(string rwfiledir,string hostname,int port,string uid,string pwd)
{
  this.hostname = hostname;
  system.out.println("正在连接"+hostname+",请等待.....");
  try{
   aftp = new ftpclient(hostname,port);
   aftp.login(uid,pwd);
   aftp.binary();
   //aftp.openportdataconnection();
   a = "连接主机:"+hostname+"成功!";
   system.out.println(a);
  }
  catch(ftploginexception e){
   a="登陆主机:"+hostname+"失败!请检查用户名或密码是否正确:"+e;
   system.out.println(a);
   //return false;
  }
  catch (ioexception e){
   a="连接主机:"+hostname+"失败!请检查端口是否正确:"+e;
   system.out.println(a);
   //return false;
  }
  catch(securityexception e)
  {
   a="无权限与主机:"+hostname+"连接!请检查是否有访问权限:"+e;
   system.out.println(a);
   //return false;
  }
  
  log(rwfiledir,a);
  return aftp;
}

public void stop(string rwfiledir)
{
  string message = "";
  try {
   if(aftp!=null){
    aftp.closeserver();
    message = "与主机"+hostname+"连接已断开!";
    system.out.println(message);
    log(rwfiledir,message);
   }
  }
  catch(ioexception e)
  {
   message = "与主机"+hostname+"断开连接失败!"+e;
   system.out.println(message);
   log(rwfiledir,message);
  }
}


public boolean downloadfile(string rwfiledir,string filepathname){
  boolean result=true;
  string message = "";
  if (aftp != null)
  {
   system.out.println("正在下载文件"+filepathname+",请等待....");
   string badfile = filepathname.substring(filepathname.length()-4,filepathname.length());
   string badlog = filepathname.substring(filepathname.length()-7,filepathname.length());
   string baddir = "";
   if ((badfile.compareto(".bad") != 0) && (badlog.compareto(".badlog") != 0)){
    baddir = "subunsubtosp//";
   }
   else{
    baddir = "bad//";
   }
   string strdir = "subunsubtosp//";
   //system.out.println(rwfiledir + baddir + filepathname);
   try{
    //ftpclient fc=new ftpclient("192.168.0.56",2121);
    //fc.login("lee","lee");
    int ch;
    file fi = new file(rwfiledir + baddir + filepathname);
    //aftp.cd(strdir);
    randomaccessfile getfile = new randomaccessfile(fi,"rw");
    getfile.seek(0);
    telnetinputstream fget=aftp.get(strdir+filepathname);
    datainputstream puts = new datainputstream(fget);
    while ((ch = puts.read()) >= 0) {
     getfile.write(ch);
     
    }
    //s.delete();
    
    fget.close();
    getfile.close();
    //fc.closeserver();

    message = "下载"+filepathname+"文件到"+baddir +"目录成功!";
    system.out.println(message);
    log(rwfiledir,message);
   }
   catch(ioexception e){
    message = "下载"+filepathname+"文件到"+baddir +"目录失败!"+e;
    system.out.println(message);
    log(rwfiledir,message);
    result = false ;

   }
  }
  else{
   result = false;
  }
  return result;
}


public boolean uploadfile(string rwfiledir,string filepathname){
  boolean result=true;
  string message = "";
  if (aftp != null)
  {
   system.out.println("正在上传文件"+filepathname+",请等待....");

   try{
    string fg =new  string("//subunsubfromsp//");
    int index = filepathname.lastindexof(fg);
    string filename = filepathname.substring(index+1);
    file localfile = new file(filepathname) ;
      
    randomaccessfile sendfile = new randomaccessfile(filepathname,"r");
    //
    sendfile.seek(0);
    //改名上传temp_
    filename = filename.substring(0,15)+"temp_"+filename.substring(15,filename.length());
    outs = aftp.put(filename);
    outputs = new dataoutputstream(outs);
    while (sendfile.getfilepointer() < sendfile.length() )
    {
     ch = sendfile.read();
     outputs.write(ch);
    }
    
    rename(filename.substring(15,filename.length()),filename.substring(20,filename.length()));
    outs.close();
    sendfile.close();
    
    message = "上传"+filepathname+"文件成功!";
    system.out.println(message);
    log(rwfiledir,message);
   }
   catch(ioexception e){
    message = "上传"+filepathname+"文件失败!"+e;
    system.out.println(message);
    log(rwfiledir,message);
    result = false ;

   }
  }
  else{
   result = false;
  }
  return result;
}

public void rename(string oldname,string newname){
  
   //aftp.renameto(oldname,newname);
   file old = new file(oldname); //oldname
   file new = new file(newname); //newname
   //aftp.renameto(new);
   //boolean old.renameto(file newname);
   //system.out.println(old);
   //system.out.println(new);
  
}

public static void delefile(string rwfiledir) {
//try {
  //取得readfile目录下的txt文件
  string sdir = rwfiledir + "subunsubfromsp//";
  file fdir = new file(sdir);
  string filename = "";
  int j = fdir.list().length;
  
  system.out.println(sdir+"目录下要删除的文件数:"+fdir.list().length);
  file  file;
  for(int i=0;i  {
   //删除subunsubfromsp中的txt文件
   filename = rwfiledir + "subunsubfromsp//" + (fdir.list())[0];
   file = new  file(filename);
   file.delete();
   system.out.println("已经成功删除"+filename+"文件!");
  }
//}
//catch (ioexception e) {
// system.out.println("删除txt文件错误!");
// e.printstacktrace();
//}
}


public void showfilecontents(string strdir)
{
  stringbuffer buf = new stringbuffer();
  try {
   aftp.cd(strdir);
   ins= aftp.list();
   while ((ch=ins.read())>=0){
    buf.append((char)ch);
   }
   
   system.out.println(buf.tostring());

   ins.close();
        }
  catch(ioexception e)
  {
  }
}



// 返回当前目录的所有文件及文件夹

public arraylist getfilelist() throws ioexception {
  bufferedreader dr = new bufferedreader(new inputstreamreader(aftp.list()));
  arraylist al = new arraylist();
  string s = "";
  while ( (s = dr.readline()) != null) {
  al.add(s);
  }
  return al;
}

public void setpath(string path) throws ioexception {
  if (aftp == null)
  this.path = path;
  else {
   aftp.cd(path);
  }
}

// 返回当前目录的文件名称

public arraylist getnamelist(string rwfiledir) throws ioexception {
  
  bufferedreader dr = new bufferedreader(new inputstreamreader(aftp.namelist("subunsubtosp//")));
  arraylist al = new arraylist();
  string s = "";
  while ( (s = dr.readline()) != null) {
   al.add(s);
   s = s.substring(13,s.length());
   isfile(s);
   downloadfile(rwfiledir,s);
   //string strfiledelf = aftp.namelist("subunsubtosp//");
   file filedelf=new file(s);
   filedelf.delete();
  }
  return al;
  //system.out.println(al.add(s));
}

// 判断一行文件信息是否为目录

public boolean isdir(string line) {
  return ( (string) parseline(line).get(0)).indexof("d") != -1;
}

public boolean isfile(string line) {
  return!isdir(line);
}

// 处理getfilelist取得的行信息

private arraylist parseline(string line) {
  arraylist s1 = new arraylist();
  stringtokenizer st = new stringtokenizer(line, " ");
  while (st.hasmoretokens()) {
   s1.add(st.nexttoken());
  }
   return s1;
}

//写消息日志
public static void log(string rwfiledir,string msg)
{
  string message = "";
  try {
   java.text.dateformat df = new java.text.simpledateformat("yyyy-mm-dd hh:mm:ss");
   java.text.dateformat dflog = new java.text.simpledateformat("yyyymmdd");
   java.util.date date = new java.util.date() ;
   string datestr = df.format(new java.util.date()) ;
   string datelog = dflog.format(new java.util.date()) ;
   //string datelog = datestr.substring(0,10);
   //datelog = datelog.replace('-',' ');

   //按日期每天生成一个日志文件
   filewriter fwl = new filewriter(rwfiledir + "cmssftp"+datelog+".log",true);
   printwriter outl = new printwriter(fwl);
   outl.println(datestr + "  " + msg);
   outl.close();
   fwl.close();
  }catch (ioexception e) {
   message = "写log文件错误!"+e;
   e.printstacktrace();
   log(rwfiledir,message);
   system.out.println(message);
  }
}
}

扫描关注微信公众号