ftpClient上传文件详解

sun.net.ftp.FtpClient.,该类库主要提供了用于建立FTP连接的类。利用这些类的方法,编程人员可以远程登录到FTP服务器,列举该服务器上的目录,设置传输协议,以及传送文件。FtpClient类涵盖了几乎所有FTP的功能,FtpClient的实例变量保存了有关建立"代理"的各种信息。下面给出了这些实例变量。

直接给大家上代码,想要用功能的直接拿过来用接可以:

import java.io.BufferedInputStream;
import java.io.BufferedReader;
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.io.OutputStream;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;



public class TfpTools {
    //连接ftp
    private FTPClient ftpClient = null;
//    public static String ip = "117.21.208.37";
//    public static int port = 21;
//    public static String username = "eftp";
//    public static String password = "e1f2t3p4";
//    public static String sub_path = "/opt/tomcat/webapps/photocdn/msgdata/";
    /**
     * 连接ftp
     */
    public void connectServer(String ip,int port,String username,String password,String sub_path) throws Exception {
        int i = 10;
        if (ftpClient == null) {
            int reply;
            while (i > 0) {
                try {
                    ftpClient = new FTPClient();
                    if (port != 21)
                        ftpClient.connect(ip, port);
                    else
                        ftpClient.connect(ip);
                    ftpClient.login(username, password);
                    reply = ftpClient.getReplyCode();
                    if (!FTPReply.isPositiveCompletion(reply)) {
                        ftpClient.disconnect();
                    }
                    System.out.println("sub_path=============="+sub_path);
                    // 对目录进行转换
                    if (ftpClient.changeWorkingDirectory(sub_path)) {
                    } else {
                        ftpClient.disconnect();
                        ftpClient = null;
                    }
                } catch (Exception e) {  
                    e.printStackTrace();
                    if (0 < i--) {
                        try {
                            Thread.sleep(10000);
                            continue;
                        } catch (Exception ex) {
                        }
                    }
                }
                i = 0;
            }
        }
    }
    /**
     * 文件上传
     * @param ip
     * @param port
     * @param username
     * @param password
     * @param sub_path                远程文件上传目录
     * @param localFilePath              本地文件存放路径、、
     * @param newFileName            远程生成的文件路径和文件名
     * @throws Exception
     */
    public void uploadFile(String ip,int port,String username,String password,String sub_path,String localFilePath, String newFileName)throws Exception {
    BufferedInputStream buffIn = null;
    try {
        connectServer(ip,port,username,password,sub_path);        //连接服务器
        System.out.println("start upload");
        buffIn = new BufferedInputStream(new FileInputStream(localFilePath));
        System.out.println("find localFilePath success");
        ftpClient.storeFile(newFileName, buffIn);
        System.out.println("upload success");
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        try {
            if (buffIn != null)
                buffIn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    }
    /**
     * 
     * Definition: 读取txt文件,存放到list中,以便于读取
     * author: xiehaoyu
     * Created date: 2013-6-14
     * @param readTxt
     * @return
     */
    public static List<String> readTxt(String readTxt){
        BufferedReader br = null;
        List<String> list = new ArrayList<String>();
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(    
                    new File(readTxt))));
            String temp = br.readLine();
            while (temp != null) {
                String[] str=temp.toString().trim().split("\\|");
                for(String s : str){
                    if(!"".equals(s))
                    list.add(s);
                }
                temp=br.readLine();
            }
            br.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
         return list;
    }
    public void copyFile(String oldPath, String newPath) {
        try {
          int bytesum = 0;
          int byteread = 0;
          File oldfile = new File(oldPath);
          if (oldfile.exists()) { //文件存在时
            InputStream inStream = new FileInputStream(oldPath); //读入原文件
            FileOutputStream fs = new FileOutputStream(newPath);
            byte[] buffer = new byte[1444];
            while ( (byteread = inStream.read(buffer)) != -1) {
              bytesum += byteread; //字节数 文件大小
              System.out.println(bytesum);
              fs.write(buffer, 0, byteread);
            }
            inStream.close();
          }
        }
        catch (Exception e) {
          System.out.println("复制单个文件操作出错");
          e.printStackTrace();

        }

    }
    
    public void delFile(String filePathAndName) {
        try {
          String filePath = filePathAndName;
          filePath = filePath.toString();
          java.io.File myDelFile = new java.io.File(filePath);
          myDelFile.delete();
        }
        catch (Exception e) {
          System.out.println("删除文件操作出错");
          e.printStackTrace();
        }
    }
    
    /**
     * 文件下载。。
     * @param url                ftp ip
     * @param port                ftp端口
     * @param username            
     * @param password
     * @param remotePath        下载路径
     * @param fileName            下载文件中包含什么文件名
     * @param localPath            本地存放路径
     * @return
     */
    public static boolean downFile(
             String url,
             int port,
             String username,
             String password,
             String remotePath,
             String fileName,
             String localPath){
     boolean success = false;
     FTPClient ftp = new FTPClient();
     try {
         int reply;
         ftp.connect(url, port);
         //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器 
         ftp.login(username, password);//登录 
         reply = ftp.getReplyCode();
         if (!FTPReply.isPositiveCompletion(reply)) {
         ftp.disconnect();
         return success;
         }
         ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
         FTPFile[] fs = ftp.listFiles();
         TfpTools fu=new TfpTools();
         for(FTPFile ff:fs){
             if(ff.getName().contains(fileName)){
                 if(fu.ToDetermineWhetherAFileExists(ff.getName())){
                 File localFile = new File(localPath+"/"+ff.getName());
                 OutputStream is = new FileOutputStream(localFile);
                 ftp.retrieveFile(ff.getName(), is);
                 is.close();
                 }
                 }
         }
             ftp.logout();
             success = true;
        } catch (IOException e) {
                  e.printStackTrace();
              } finally {
                    if (ftp.isConnected()) {
                        try {
                             ftp.disconnect();
                         } catch (IOException ioe) {
                         }
                     }
                }
                  return success;
    } 
    
    public boolean ToDetermineWhetherAFileExists(String fileName){
        boolean flag=true;
        Vector<String> v=new Vector<String>();
        v=GetTestXlsFileName("c:/JX_jiekou/src/backups");
        for(int i=0;i<v.size();i++){
            String str=(String)v.elementAt(i);
            if(str.equals(fileName)){
                flag=false;
            }
        }
        return flag;
    }
    /**
     * 读取本地某个目录下,所有txt文件的文件名
     * @param fileAbsolutePath        本地文件目录。
     * @return
     */
    public static Vector<String> GetTestXlsFileName(String fileAbsolutePath) {
        Vector<String> vecFile = new Vector<String>();
        File file = new File(fileAbsolutePath);
        File[] subFile = file.listFiles();
 
        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
           // 判断是否为文件夹 
           if (!subFile[iFileLength].isDirectory()) {
               String fileName = subFile[iFileLength].getName();
               // 判断是否为.txt结尾 
                if (fileName.trim().toLowerCase().endsWith(".txt")) {
                   vecFile.add(fileName);
                }
           }
       }
        return vecFile;
   }
    
    public boolean truncateTable(String tableName){
        Connection conn=null;
        Statement sm=null;
        String sql="truncate table "+tableName;
        try {
            conn=DBConfig.getConn(JkConfig.getDb_url(),JkConfig.getDb_username(),JkConfig.getDb_password(),0);
            sm=conn.createStatement();
            sm.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
    return true;
    }
    public void closeConnect() {
        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();
                ftpClient=null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

posted on 2013-11-12 14:09  谢皓宇  阅读(3205)  评论(0编辑  收藏  举报

导航