问征夫以前路
感谢所有关心过支持过我的人, 感谢所有恨过我嘲笑过我的人 !
posts - 30,comments - 147,trackbacks - 0

        近日在做FTP的上传下载功能,此功能几经周折,终于实现单线程和多线程文件的上传和下载,我现在把代码上传,算是一个OK的demo

package com.cotel.service.gather;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Properties;
import org.apache.log4j.*;
import com.cotel.parse.ParseXML;
import com.cotel.util.FileFinder;

import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;


/**
 * 
 * 功能描述:FTP上传和下载
 *      
 * 
@author <a href="mailto:zhanghhui@126.com">KenZhang</a>
 * 
@version 1.0 
 * Creation date: 2007-8-22 - 下午04:57:32
 
*/

public class GatherServiceImpl implements IGatherService{
    
//引入日志
    private static Logger log = (Logger)Logger.getLogger(GatherServiceImpl.class);
     
/** 
     * 类的初始化,建立ftp的连接,用户登录,指定ftp的传输流
     * 
@param host
     * 
@param port
     * 
@param user
     * 
@param psw
     
*/

//    建立一条与指定主机、指定端口上的FTP服务器的连接
    private FtpClient aftp = new FtpClient();
    
private DataOutputStream outputs;
    
private TelnetOutputStream outs;
    
private TelnetInputStream inps;
    
    
//此路径只应用于在java Application里面进行调试
    private static String path = System.getProperty("user.dir"+ "\\WebRoot\\WEB-INF\\classes\\charging\\";

    
//在tomcat里面运行时用下面路径----
//    private static String path = GatherServiceImpl.class.getClass().getResource("/").getPath()+ "charging";
    
    
    
public void FTPClass(String host,String port,String user,String psw,String url){
        
        
try{
            
//   注册到FTP服务器
            aftp.openServer(host);
            log.debug(
"登陆.");
            aftp.login(user,psw);
            log.debug(
"登录FTP服务器成功!");
            aftp.binary();
        }
catch(IOException e){
            log.debug(
"连接FTP服务器失败!");
            e.printStackTrace();
        }

    }

        
    
/** 
     * 通过ftp上传文件到服务器上
     * 
@param localFile 本地所要上传的文件
     * 
@param remoteFile 传到服务器上的文件名称
     
*/

    
public boolean upFile(String localFile,String remoteFile){
        
boolean result = true;
        
if(aftp != null){
            log.debug(
"正在上传文件"+localFile+",请稍等.");
            
try{
                File file 
= new File(localFile);
                outs 
= aftp.put(remoteFile);
                FileInputStream in 
= new FileInputStream(file);
                
byte[] bytes = new byte[1024];
                
int c;
                
while((c = in.read(bytes))!=-1){
                    outs.write(bytes,
0,c);
                    }

                outs.close();
                in.close();
                log.debug(
"上传文件"+localFile+"成功!");
                log.debug(
"上传文件所在目录:"+remoteFile+"");
                }
catch(Exception e){
                    e.printStackTrace();
                    log.debug(
"上传文件"+localFile+"失败!");
                    result 
= false;
                }

            }
else{
                result 
= false;
                }

                
return result;
        }

        
    
/** 
     * 下载FTP服务器上的文件
     * 
@param localFile 本地文件名
     * 
@param remoteFile 远程服务器文件名
     
*/

    
public boolean downFile(String remoteFile,String localFile){
        
boolean result = true;
        log.debug(
"begin");
        
if(aftp!=null){
            log.debug(
"正在下载文件"+remoteFile+",请等待");
            
try
                log.debug("===" + remoteFile);
                inps 
= aftp.get(remoteFile);                    
                FileInputStream in 
= null;
                FileOutputStream os;
                
if(inps != null){                    
                    os 
= new FileOutputStream(localFile);
                    
byte[] bytes = new byte [1024];
                    
int c ;
                    
while ((c = inps.read(bytes))!=-1){
                    os.write(bytes,
0,c);
                    log.debug(c);
                    }

                inps.close();
                os.close();
                }
else
                    log.debug(
"file not exist!");
            inps.close();
        
            log.debug(
"下载文件"+localFile+"成功!");
            log.debug(
"下载文件所在目录:"+localFile+"");
            }
catch(Exception e){
                    e.printStackTrace();
                    log.debug(
"下载文件"+localFile+"失败!");
                    result 
= false;
                }

            }

            
return false;
        }
    
    
    
/**
     * 断开ftp连接
     * 
@throws IOException 
     *
     
*/

    
public void disconnect() throws IOException{
        aftp.closeServer();
        log.debug(
"FTP服务器连接断开!");
        }
    
    
    
// 返回当前目录的所有文件及文件夹
    public ArrayList getFileList() throws IOException{
        BufferedReader dr 
= new BufferedReader(new InputStreamReader(aftp.nameList("*.txt")));
        ArrayList al 
= new ArrayList();
        String s 
= "";
        
while ((s=dr.readLine())!=null){
            al.add(s);
            }

        
return al;
        }


    
/**    main方法测试
     * 
@param args
     * 
@throws IOException
     * 
@author <a href="mailto:zhanghhui@126.com">KenZhang</a>
     * Creation date: 2007-8-23 - 上午10:11:03
     
*/

    
public static void main(String[] args) throws IOException{
        GatherServiceImpl gatherService 
= new GatherServiceImpl();
        log.debug(
"begin");
        
         
//从配置文件中获得监听端口和发送端口
          Properties p = new Properties();
          
//读取配置文件
          InputStream in = GatherServiceImpl.class.getResourceAsStream(
              
"/config.properties");
          p.load(in);
          in.close();
          String ftpHostIP 
= p.getProperty("ftpHostIP");
          String ftpPort 
= p.getProperty("ftpPort");
          String ftpUserName 
= p.getProperty("ftpUserName");
          String ftpPassWord 
= p.getProperty("ftpPassWord");
          String ftpPath 
= p.getProperty("ftpPath");
          gatherService.FTPClass(ftpHostIP, ftpPort, ftpUserName, ftpPassWord, ftpPath);
          
          
//文件批量下载,把扩展名为.txt的所有文件一次下载到服务器
          ArrayList list = gatherService.getFileList();
          
for(int i = 0; i < list.size(); i++){
              String fileName 
= null;
              fileName 
= (String)list.get(i);
              
//System.out.println("-------"+fileName);
              gatherService.downFile(fileName,path+fileName);
          }

          
        
//文件进行批量上传,把扩展名为.txt的所有文件一次上传到服务器
        FileFinder fileFinder = new FileFinder();
        File[] files 
= fileFinder.getFilesBySuffix(".txt", path);
        
for (int i = 0; i < files.length; i++{            
            System.out.println(
"-------"+files[i].getName());
            gatherService.upFile(path
+files[i].getName(),files[i].getName());
        }

        
        
//从ftp服务器下载文件
        
//  gatherService.downFile("地标信息.txt",path+"地标信息.txt");
        
//上传文件到ftp服务器
        
//ftpClient.upFile(path+"地标信息.txt", "ftproot/地标信息.txt");
        
        
//与FTP服务器连接断开
          gatherService.disconnect();

}

         代码改动很多,才实现了我想要的需求。用java Application运行的时候是不是有缓存呢?有的话,这个缓存怎么去呢?我都是再把程序重新编译一次,再执行。好像起点作用!
posted on 2007-08-31 16:01 kenzhang 阅读(642) 评论(1)  编辑  收藏

FeedBack:
# re: FTP实现上传下载
2007-12-01 22:00 | 未来之我制作
好啊 这些代码恰到好处啊

我要以此作为参考代码学习啊   回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: