java连接FTP、删除、下载文件的工具类

目前例举了二个连接FTP的方法,可以下载删除FTP上的文件,代码目前有点凌乱,以后再优化

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

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

/*
 * Copyright (C) 2011-2014 dshine.com
 * All rights reserved.
 */
/**
 * @author Wiker Yong Email:<a href="mailto:[email protected]">[email protected]</a>
 * @date 2014-8-19 下午2:00:58
 * @version 1.0-SNAPSHOT
 */
publicclassJavaFtpClient{
    privateStringip="";
    privateStringusername="";
    privateStringpassword="";
    privateintport=-1;
    privateStringpath="";
    FtpClientftpClient=null;
    OutputStreamos=null;
    FileInputStreamis=null;
    staticStringcurFolder=System.getProperty("user.dir");
    privatefinalstaticLogger log =Logger.getLogger(JavaFtpClient.class);

    // LogInfologinfo = new LogInfo();

    publicJavaFtpClient(String serverIP,String username,String password){
        this.ip= serverIP;
        this.username= username;
        this.password= password;
    }

    publicJavaFtpClient(String serverIP,int port,String username,String password){
        this.ip= serverIP;
        this.username= username;
        this.password= password;
        this.port= port;
    }

    publicvoidsetPath(String path)
            throws IOException {
        if(ftpClient==null){
            this.path= path;
        }else{
            ftpClient.cd(path);
        }
    }

    /**
     * 连接ftp服务器
     *
     * @throws IOException
     */
    publicbooleanconnectServer(){
        if(ftpClient!=null){
            returntrue;
        }
        ftpClient=newFtpClient();
        try{
            if(this.port!=-1){
                ftpClient.openServer(this.ip,this.port);
            }else{
                ftpClient.openServer(this.ip);
            }
            ftpClient.login(this.username,this.password);
            if(this.path.length()!=0){
                ftpClient.cd(this.path);// path是ftp服务下主目录的子目录
            }
            ftpClient.binary();// 用2进制上传、下载
            log.info("FTP 已登录到\""+ftpClient.pwd()+"\"目录");
            // loginfo.appendLog("FTP 已登录到\"" + ftpClient.pwd() + "\"目录");

            returntrue;
        }catch(IOException e){
            log.error(e.getMessage(), e);
            returnfalse;
        }
    }

    /**
     * 断开与ftp服务器连接
     *
     * @throws IOException
     */
    publicbooleancloseServer(){
        try{
            if(is!=null){
                is.close();
            }
            if(os!=null){
                os.close();
            }
            if(ftpClient!=null){
                ftpClient.closeServer();
            }
            log.info("已从服务器断开");
            // loginfo.appendLog("已从服务器断开");
            returntrue;
        }catch(IOException e){
            e.printStackTrace();
            returnfalse;
        }
    }

    /**
     * 检查文件夹在当前目录下是否存在
     *
     * @param dir
     * @return
     */
    publicbooleanisDirExist(String dir){
        String pwd ="";
        try{
            pwd =ftpClient.pwd();
            ftpClient.cd(dir);
            ftpClient.cd(pwd);
        }catch(Exception e){
            returnfalse;
        }
        returntrue;
    }

    publicbooleanrename(String str1,String str2)
            throws IOException {
        String file1 ="";
        String file2 ="";
        String folder1 ="";
        String folder2 ="";
        file1 = str1.substring(str1.lastIndexOf("/")+1, str1.length());
        file2 = str2.substring(str2.lastIndexOf("/")+1, str2.length());
        folder1 = str1.substring(0, str1.lastIndexOf("/")+1);
        folder2 = str2.substring(0, str2.lastIndexOf("/")+1);
        if(!isDirExist(folder2)){
            createDir(folder2);
        }
        ftpClient.rename(str1, str2);
        List l =this.getFileList(folder2);
        for(int i =0; i < l.size(); i++){
            if(l.get(i).toString().indexOf(file2)>0){
                returntrue;
            }
        }
        returnfalse;
    }

    publicvoidsendCMD(String cmd)
            throws IOException {
        ftpClient.sendServer(cmd);
        log.info(cmd.replaceAll("\r\n","\\\\r\\\\n"));
        int reply =ftpClient.readServerResponse();
        log.info("Server Response:"+ reply);
        // log.info(reply);
    }

    /**
     * 在当前目录下创建文件夹
     *
     * @param dir
     * @return
     * @throws Exception
     */
    privatebooleancreateDir(String dir){
        try{
            ftpClient.ascii();
            StringTokenizer s =newStringTokenizer(dir,"/");// sign
            s.countTokens();
            String pathName ="";//ftpClient.pwd();
            while(s.hasMoreElements()){
                pathName = pathName +"/"+(String) s.nextElement();
                if(this.isDirExist(pathName)){
                    continue;
                }
                try{
                    ftpClient.sendServer("MKD "+ pathName +"\r\n");
                }catch(Exception e){
                    e =null;
                    returnfalse;
                }
                ftpClient.readServerResponse();
            }
            ftpClient.binary();
            returntrue;
        }catch(IOException e1){
            e1.printStackTrace();
            returnfalse;
        }
    }

    /**
     * ftp上传如果服务器段已存在名为filename的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换
     *
     * @param filename
     *            要上传的文件(或文件夹)名
     * @return
     * @throws Exception
     */
    publicbooleanupload(String filename){
        String newname ="";
        if(filename.indexOf("/")>-1){
            newname = filename.substring(filename.lastIndexOf("/")+1);
        }else{
            newname = filename;
        }
        returnupload(filename, newname);
    }

    /**
     * ftp上传如果服务器段已存在名为newName的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换
     *
     * @param fileName
     *            要上传的文件(或文件夹)名
     * @param newName
     *            服务器段要生成的文件(或文件夹)名
     * @return
     */
    publicbooleanupload(String fileName,String newName){
        try{
            String savefilename =newString(fileName.getBytes("ISO-8859-1"),"GBK");
            File file_in =newFile(savefilename);// 打开本地待长传的文件
            if(!file_in.exists()){
                thrownewException("此文件或文件夹["+ file_in.getName()+"]有误或不存在!");
            }
            if(file_in.isDirectory()){
                upload(file_in.getPath(), newName,ftpClient.pwd());
            }else{
                uploadFile(file_in.getPath(), newName);
            }

            if(is!=null){
                is.close();
            }
            if(os!=null){
                os.close();
            }
            returntrue;
        }catch(Exception e){
            e.printStackTrace();
            System.err.println("Exception ein Ftp upload(): "+ e.toString());
            returnfalse;
        }finally{
            try{
                if(is!=null){
                    is.close();
                }
                if(os!=null){
                    os.close();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 真正用于上传的方法
     *
     * @param fileName
     * @param newName
     * @param path
     * @throws Exception
     */
    privatevoidupload(String fileName,String newName,String path)
            throws Exception {
        String savefilename =newString(fileName.getBytes("ISO-8859-1"),"GBK");
        File file_in =newFile(savefilename);// 打开本地待长传的文件
        if(!file_in.exists()){
            thrownewException("此文件或文件夹["+ file_in.getName()+"]有误或不存在!");
        }
        if(file_in.isDirectory()){
            if(!isDirExist(newName)){
                createDir(newName);
            }
            ftpClient.cd(newName);
            File sourceFile[]= file_in.listFiles();
            for(int i =0; i < sourceFile.length; i++){
                if(!sourceFile[i].exists()){
                    continue;
                }
                if(sourceFile[i].isDirectory()){
                    this.upload(sourceFile[i].getPath(), sourceFile[i].getName(), path +"/"
                            + newName);
                }else{
                    this.uploadFile(sourceFile[i].getPath(), sourceFile[i].getName());
                }
            }
        }else{
            uploadFile(file_in.getPath(), newName);
        }
        ftpClient.cd(path);
    }

    /**
     * upload 上传文件
     *
     * @param filename
     *            要上传的文件名
     * @param newname
     *            上传后的新文件名
     * @return-1 文件不存在 >=0 成功上传,返回文件的大小
     * @throws Exception
     */
    publiclonguploadFile(String filename,String newname)
            throws Exception {
        long result =0;
        TelnetOutputStream os =null;
        FileInputStream is =null;
        try{
            java.io.File file_in =new java.io.File(filename);
            if(!file_in.exists()){
                return-1;
            }
            os =ftpClient.put(newname);
            result = file_in.length();
            is =newFileInputStream(file_in);
            byte[] bytes =newbyte[1024];
            int c;
            while((c = is.read(bytes))!=-1){
                os.write(bytes,0, c);
            }
        }finally{
            if(is !=null){
                is.close();
            }
            if(os !=null){
                os.close();
            }
        }
        return result;
    }

    /**
     * 从ftp下载文件到本地
     *
     * @param filename
     *            服务器上的文件名
     * @param newfilename
     *            本地生成的文件名
     * @return
     * @throws Exception
     */
    publiclongdownloadFile(String filename,String newfilename){
        long result =0;
        TelnetInputStream is =null;
        FileOutputStream os =null;
        try{
            is =ftpClient.get(filename);
            java.io.File outfile =new java.io.File(newfilename);
            log.info("Download File:"+ outfile.getPath());
            os =newFileOutputStream(outfile);
            byte[] bytes =newbyte[1024];
            int c;
            while((c = is.read(bytes))!=-1){
                os.write(bytes,0, c);
                result = result + c;
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            try{
                if(is !=null){
                    is.close();
                }
                if(os !=null){
                    os.close();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 取得相对于当前连接目录的某个目录下所有文件列表
     *
     * @param path
     * @return
     */
    publicListgetFileList(String path){
        List list =newArrayList();
        DataInputStream dis;
        try{
            log.info(this.path+ path);
            dis =newDataInputStream(ftpClient.nameList(this.path+ path));
            String filename ="";
            while((filename = dis.readLine())!=null){
                String sfilename =newString(filename.getBytes("ISO-8859-1"),"utf-8");
                list.add(sfilename);
            }
        }catch(IOException e){
            e.printStackTrace();
        }
        return list;
    }

    publicstaticvoidmain(String[] args)
            throws IOException {
        workPath=JavaFtpClient.class.getClass().getResource("/").getPath();
        String tempFolder = getPropertiesValueByKey(workPath+"/application.properties",
                "download.path");
        File file =newFile(tempFolder);
        if(!file.exists()){
            file.mkdir();
        }
        String ftpIp = getPropertiesValueByKey(workPath+"/application.properties","ftp.ip");
        String port = getPropertiesValueByKey(workPath+"/application.properties","ftp.port");
        String user = getPropertiesValueByKey(workPath+"/application.properties","ftp.user");
        String password = getPropertiesValueByKey(workPath+"/application.properties",
                "ftp.password");
        String sleep = getPropertiesValueByKey(workPath+"/application.properties","sleep.time");
        sleep =StringUtils.defaultIfEmpty(sleep,"3600");

        while(true){
            JavaFtpClient ftp =newJavaFtpClient(ftpIp,Integer.valueOf(port), user, password);
            ftp.setPath("/");
            ftp.connectServer();

            // boolean result = ftp.upload("D:/4500000436.XML", "/sapinstall/MMIWM/4500000436.XML");
            // log.info(result ? "上传成功!" : "上传失败!");

            List list = ftp.getFileList("/");
            for(int i =0; i < list.size(); i++){
                // String name = newString(list.get(i).toString().getBytes("UTF-8"), "iso-8859-1");
                String name = list.get(i).toString();
                // log.info(name);
                if(!ftp.isDirExist(name)){
                    ftp.downloadFile(
                            name,
                            tempFolder +"\\"
                                    + name.substring(name.lastIndexOf("/")+1, name.length()));
                    ftp.sendCMD("DELE "+ name.substring(name.lastIndexOf("/")+1, name.length())
                            +"\r\n");
                }
            }
            ftp.closeServer();
            try{
                log.info("休眠 "+ sleep +" 秒");
                Thread.sleep(Integer.valueOf(sleep)*1000);
            }catch(NumberFormatException e){
                // TODO Auto-generated catch block
                e.printStackTrace();
            }catch(InterruptedException e){
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        /**
         * FTP远程命令列表 USER PORT RETR ALLO DELE SITE XMKD CDUP FEAT PASS PASVSTOR
         * REST CWD STAT RMD XCUP OPTS ACCTTYPE APPE RNFR XCWD HELP XRMD STOU
         * AUTH REIN STRU SMNT RNTO LIST NOOPPWD SIZE PBSZ QUIT MODE SYST ABOR
         * NLST MKD XPWD MDTM PROT
         * 在服务器上执行命令,如果用sendServer来执行远程命令(不能执行本地FTP命令)的话,所有FTP命令都要加上\r\n
         * ftpclient.sendServer("XMKD/test/bb\r\n"); //执行服务器上的FTP命令
         * ftpclient.readServerResponse一定要在sendServer后调用
         * nameList("/test")获取指目录下的文件列表 XMKD建立目录,当目录存在的情况下再次创建目录时报错 XRMD删除目录
         * DELE删除文件
         */
    }

    staticStringworkPath=null;

    publicstaticStringgetPropertiesValueByKey(String fileName,String key){
        Properties p =newProperties();
        String value ="";
        try{
            InputStream in =newBufferedInputStream(newFileInputStream(fileName));
            p.load(in);
            value = p.getProperty(key);
        }catch(Exception e){
            e.printStackTrace();
            return"";
        }
        return value;
    }

}

Apache库的方法
需要依赖commons-net-3.1.jar库可以apache官方下载
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.StringTokenizer;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;

/*
 * Copyright (C) 2011-2014 dshine.com
 * All rights reserved.
 * ShangHai Dshine -http://www.dshine.com
 */
/**
 * @author Wiker Yong Email:<a href="mailto:[email protected]">[email protected]</a>
 * @date 2014-8-19 下午2:00:58
 * @version 1.0-SNAPSHOT
 */
publicclassApacheFtpClient{
    privateStringip="";
    privateStringusername="";
    privateStringpassword="";
    privateintport=-1;
    privateStringpath="";
    FTPClientftpClient=null;
    OutputStreamos=null;
    FileInputStreamis=null;
    staticStringcurFolder=System.getProperty("user.dir");
    privatefinalstaticLogger log =Logger.getLogger(ApacheFtpClient.class);

    // LogInfologinfo = new LogInfo();

    publicApacheFtpClient(String serverIP,String username,String password){
        this.ip= serverIP;
        this.username= username;
        this.password= password;
    }

    publicApacheFtpClient(String serverIP,int port,String username,String password){
        this.ip= serverIP;
        this.username= username;
        this.password= password;
        this.port= port;
    }

    publicvoidsetPath(String path)
            throws IOException {
        if(ftpClient==null){
            this.path= path;
        }else{
            ftpClient.cwd(path);
        }
    }

    /**
     * 连接ftp服务器
     *
     * @throws IOException
     */
    publicbooleanconnectServer(){
        if(ftpClient!=null){
            returntrue;
        }
        ftpClient=newFTPClient();
        try{
            if(this.port!=-1){
                ftpClient.connect(this.ip,this.port);
            }else{
                ftpClient.connect(this.ip);
            }
            ftpClient.setControlEncoding("UTF-8");
            ftpClient.login(this.username,this.password);
            if(this.path.length()!=0){
                ftpClient.cwd(this.path);// path是ftp服务下主目录的子目录
            }
            //ftpClient.binary();// 用2进制上传、下载
            ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
            log.info("FTP 已登录到\""+ftpClient.pwd()+"\"目录");
            // loginfo.appendLog("FTP 已登录到\"" + ftpClient.pwd() + "\"目录");

            returntrue;
        }catch(IOException e){
            log.error(e.getMessage(), e);
            returnfalse;
        }
    }

    /**
     * 断开与ftp服务器连接
     *
     * @throws IOException
     */
    publicbooleancloseServer(){
        try{
            if(is!=null){
                is.close();
            }
            if(os!=null){
                os.close();
            }
            if(ftpClient!=null){
                ftpClient.disconnect();
            }
            log.info("已从服务器断开");
            // loginfo.appendLog("已从服务器断开");
            returntrue;
        }catch(IOException e){
            e.printStackTrace();
            returnfalse;
        }
    }

    /**
     * 检查文件夹在当前目录下是否存在
     *
     * @param dir
     * @return
     */
    publicbooleanisDirExist(String dir){
        String pwd ="";
        try{
            //pwd = ftpClient.pwd();
            ftpClient.cwd(dir);
            ftpClient.cwd(pwd);
        }catch(Exception e){
            returnfalse;
        }
        returntrue;
    }

//    public boolean rename(String str1, Stringstr2)
//            throws IOException {
//        String file1 = "";
//        String file2 = "";
//        String folder1 = "";
//        String folder2 = "";
//        file1 =str1.substring(str1.lastIndexOf("/") + 1, str1.length());
//        file2 =str2.substring(str2.lastIndexOf("/") + 1, str2.length());
//        folder1 = str1.substring(0,str1.lastIndexOf("/") + 1);
//        folder2 = str2.substring(0, str2.lastIndexOf("/")+ 1);
//        if (!isDirExist(folder2)) {
//            createDir(folder2);
//        }
//        ftpClient.rename(str1, str2);
//        List l = this.getFileList(folder2);
//        for (int i = 0; i < l.size();i++) {
//            if(l.get(i).toString().indexOf(file2) > 0) {
//                return true;
//            }
//        }
//        return false;
//    }

    publicvoidsendCMD(String cmd)
            throws IOException {
        ftpClient.sendCommand(cmd);
        log.info(cmd.replaceAll("\r\n","\\\\r\\\\n"));
        int reply =ftpClient.getReply();
        log.info("Server Response:"+ reply);
        // log.info(reply);
    }

    /**
     * 在当前目录下创建文件夹
     *
     * @param dir
     * @return
     * @throws Exception
     */
    privatebooleancreateDir(String dir){
        try{
            ftpClient.setFileTransferMode(FTP.ASCII_FILE_TYPE);
            StringTokenizer s =newStringTokenizer(dir,"/");// sign
            s.countTokens();
            String pathName ="";//ftpClient.pwd();
            while(s.hasMoreElements()){
                pathName = pathName +"/"+(String) s.nextElement();
                if(this.isDirExist(pathName)){
                    continue;
                }
                try{
                    ftpClient.sendCommand("MKD "+ pathName +"\r\n");
                }catch(Exception e){
                    e =null;
                    returnfalse;
                }
                ftpClient.getReply();
            }
            ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
            returntrue;
        }catch(IOException e1){
            e1.printStackTrace();
            returnfalse;
        }
    }

    /**
     * ftp上传如果服务器段已存在名为filename的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换
     *
     * @param filename
     *            要上传的文件(或文件夹)名
     * @return
     * @throws Exception
     */
    /*publicboolean upload(String filename) {
        String newname = "";
        if (filename.indexOf("/")> -1) {
            newname =filename.substring(filename.lastIndexOf("/") + 1);
        } else {
            newname = filename;
        }
        return upload(filename, newname);
    }*/

    /**
     * ftp上传如果服务器段已存在名为newName的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换
     *
     * @param fileName
     *            要上传的文件(或文件夹)名
     * @param newName
     *            服务器段要生成的文件(或文件夹)名
     * @return
     */
    /*publicboolean upload(String fileName, String newName) {
        try {
            String savefilename = newString(fileName.getBytes("ISO-8859-1"), "GBK");
            File file_in = new File(savefilename);//打开本地待长传的文件
            if (!file_in.exists()) {
                throw new Exception("此文件或文件夹[" + file_in.getName() + "]有误或不存在!");
            }
            if (file_in.isDirectory()) {
                upload(file_in.getPath(),newName, ftpClient.pwd());
            } else {
                uploadFile(file_in.getPath(),newName);
            }

            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Exceptione in Ftp upload(): " + e.toString());
            return false;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }*/

    /**
     * 真正用于上传的方法
     *
     * @param fileName
     * @param newName
     * @param path
     * @throws Exception
     */
    /*privatevoid upload(String fileName, String newName, String path)
            throws Exception {
        String savefilename = newString(fileName.getBytes("ISO-8859-1"), "GBK");
        File file_in = new File(savefilename);//打开本地待长传的文件
        if (!file_in.exists()) {
            throw new Exception("此文件或文件夹[" + file_in.getName() + "]有误或不存在!");
        }
        if (file_in.isDirectory()) {
            if (!isDirExist(newName)) {
                createDir(newName);
            }
            ftpClient.cwd(newName);
            File sourceFile[] =file_in.listFiles();
            for (int i = 0; i <sourceFile.length; i++) {
                if (!sourceFile[i].exists()) {
                    continue;
                }
                if(sourceFile[i].isDirectory()) {
                   this.upload(sourceFile[i].getPath(), sourceFile[i].getName(), path +"/"
                            + newName);
                } else {
                   this.uploadFile(sourceFile[i].getPath(), sourceFile[i].getName());
                }
            }
        } else {
            uploadFile(file_in.getPath(),newName);
        }
        ftpClient.cwd(path);
    }*/

    /**
     * upload 上传文件
     *
     * @param filename
     *            要上传的文件名
     * @param newname
     *            上传后的新文件名
     * @return-1 文件不存在 >=0 成功上传,返回文件的大小
     * @throws Exception
     */
    /*publiclong uploadFile(String filename, String newname)
            throws Exception {
        long result = 0;
        TelnetOutputStream os = null;
        FileInputStream is = null;
        try {
            java.io.File file_in = newjava.io.File(filename);
            if (!file_in.exists()) {
                return -1;
            }
            os = ftpClient.put(newname);
            result = file_in.length();
            is = new FileInputStream(file_in);
            byte[] bytes = new byte[1024];
            int c;
            while ((c = is.read(bytes)) != -1){
                os.write(bytes, 0, c);
            }
        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        }
        return result;
    }*/

    /**
     * 从ftp下载文件到本地
     *
     * @param filename
     *            服务器上的文件名
     * @param newfilename
     *            本地生成的文件名
     * @return
     * @throws Exception
     */
    publicbooleandownloadFile(String filename,String newfilename){
        long result =0;
        InputStream is =null;
        FileOutputStream os =null;
        try{
            filename =newString(filename.getBytes("UTF-8"),"ISO-8859-1");
            is =ftpClient.retrieveFileStream(filename);
            java.io.File outfile =new java.io.File(newfilename);
            if(!outfile.getParentFile().exists()){
                outfile.getParentFile().mkdirs();
            }
            log.info("Download File:"+ outfile.getPath());
            os =newFileOutputStream(outfile);
            byte[] bytes =newbyte[1024];
            int c;
            while((c = is.read(bytes))!=-1){
                os.write(bytes,0, c);
                result = result + c;
            }
            returnftpClient.completePendingCommand();
        }catch(IOException e){
            log.error(e.getMessage(), e);
        }finally{
            try{
                if(is !=null){
                    is.close();
                }
                if(os !=null){
                    os.close();
                }
            }catch(IOException e){
                log.error(e.getMessage(), e);
            }
        }
        returnfalse;
    }

    /**
     * 取得相对于当前连接目录的某个目录下所有文件列表
     *
     * @param path
     * @return
     */
   /* publicList getFileList(String path) {
        List list = new ArrayList();
        DataInputStream dis;
        try {
            log.info(this.path + path);
            dis = newDataInputStream(ftpClient.li.nameList(this.path + path));
            String filename = "";
            while ((filename = dis.readLine())!= null) {
                String sfilename = newString(filename.getBytes("ISO-8859-1"), "utf-8");
                list.add(sfilename);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }*/

    publicstaticvoidmain(String[] args)
            throws IOException {
        workPath=ApacheFtpClient.class.getClass().getResource("/").getPath();
        String tempFolder = getPropertiesValueByKey(workPath+"/application.properties",
                "download.path");
        File file =newFile(tempFolder);
        if(!file.exists()){
            file.mkdir();
        }
        String ftpIp = getPropertiesValueByKey(workPath+"/application.properties","ftp.ip");
        String port = getPropertiesValueByKey(workPath+"/application.properties","ftp.port");
        String user = getPropertiesValueByKey(workPath+"/application.properties","ftp.user");
        String password = getPropertiesValueByKey(workPath+"/application.properties",
                "ftp.password");
        String sleep = getPropertiesValueByKey(workPath+"/application.properties","sleep.time");
        sleep =StringUtils.defaultIfEmpty(sleep,"3600");

        //String[] reqPathArr ={"/add/request","/all/request"};
        String addReqPath ="/add/request";
        String allReqPath ="/all/request";

        //readAllReq("D:\\temp\\add\\request\\SubscribeInfo000329522012082014060510824.req");

        while(true){

            {
                ApacheFtpClient ftp =newApacheFtpClient(ftpIp,Integer.valueOf(port), user, password);
                ftp.setPath(addReqPath);
                ftp.connectServer();

                // boolean result = ftp.upload("D:/4500000436.XML", "/sapinstall/MMIWM/4500000436.XML");
                // log.info(result ? "上传成功!" : "上传失败!");

                FTPFile[] list = ftp.ftpClient.listFiles();
                for(FTPFile ftpfile :list){
                    if(ftpfile.isFile()){

                        String localPath = tempFolder +addReqPath+"/"
                                + ftpfile.getName();
                        ftp.downloadFile(
                                ftpfile.getName(),localPath);
                        String delfileName =newString(ftpfile.getName().getBytes("UTF-8"),"ISO-8859-1");
                        log.info("DELEfile:"+addReqPath+"/"+ftpfile.getName());

                        readAddReq(localPath);
                        ftp.ftpClient.deleteFile(addReqPath+"/"+delfileName);
                    }
                    //log.info(ftpfile.getName());
                }
                ftp.closeServer();
            }

            {
                ApacheFtpClient ftp =newApacheFtpClient(ftpIp,Integer.valueOf(port), user, password);
                ftp.setPath(allReqPath);
                ftp.connectServer();

                // boolean result = ftp.upload("D:/4500000436.XML", "/sapinstall/MMIWM/4500000436.XML");
                // log.info(result ? "上传成功!" : "上传失败!");

                FTPFile[] list = ftp.ftpClient.listFiles();
                for(FTPFile ftpfile :list){
                    if(ftpfile.isFile()){
                        String localPath = tempFolder +addReqPath+"/"
                                + ftpfile.getName();
                        ftp.downloadFile(
                                ftpfile.getName(),localPath);
                        String delfileName =newString(ftpfile.getName().getBytes("UTF-8"),"ISO-8859-1");
                        log.info("DELEfile:"+allReqPath+"/"+ftpfile.getName());

                        readAllReq(localPath);
                        ftp.ftpClient.deleteFile(allReqPath+"/"+delfileName);
                    }
                    //log.info(ftpfile.getName());
                }
                ftp.closeServer();
            }
            try{
                log.info("休眠 "+ sleep +" 秒");
                Thread.sleep(Integer.valueOf(sleep)*1000);
            }catch(NumberFormatException e){
                log.error(e.getMessage(), e);
            }catch(InterruptedException e){
                log.error(e.getMessage(), e);
            }
        }

        /**
         * FTP远程命令列表 USER PORT RETR ALLO DELE SITE XMKD CDUP FEAT PASS PASVSTOR
         * REST CWD STAT RMD XCUP OPTS ACCTTYPE APPE RNFR XCWD HELP XRMD STOU
         * AUTH REIN STRU SMNT RNTO LIST NOOPPWD SIZE PBSZ QUIT MODE SYST ABOR
         * NLST MKD XPWD MDTM PROT
         * 在服务器上执行命令,如果用sendServer来执行远程命令(不能执行本地FTP命令)的话,所有FTP命令都要加上\r\n
         * ftpclient.sendServer("XMKD/test/bb\r\n"); //执行服务器上的FTP命令
         * ftpclient.readServerResponse一定要在sendServer后调用
         * nameList("/test")获取指目录下的文件列表 XMKD建立目录,当目录存在的情况下再次创建目录时报错 XRMD删除目录
         * DELE删除文件
         */
    }

    publicstaticConnectiongetConnection(){
        int time =0;
        Connection conn =null;
        do{
            try{
                Class.forName(getPropertiesValueByKey(workPath
                        +"/application.properties","className"));
                conn =DriverManager.getConnection(
                        getPropertiesValueByKey(workPath
                                +"/application.properties","connUrl"),
                        getPropertiesValueByKey(workPath
                                +"/application.properties","userName"),
                        getPropertiesValueByKey(workPath
                                +"/application.properties","password"));
                log.debug("数据库连接成功");
                break;
            }catch(Exception e){
                log.error("数据库连接失败",e);
                time ++;
                try{
                    Thread.sleep(3000);
                }catch(InterruptedException e1){
                    e1.printStackTrace();
                }
            }
        }while(time<3);
        return conn;
    }

    publicstaticvoidreadAllReq(String path){
        log.info("Read all request file:"+path);
        BufferedReader reader =null;
        Connection con = getConnection();// 数据连接
        try{
            log.info("Read file:"+path);
            File file =newFile(path);
            reader =newBufferedReader(newFileReader(file));
            int line =1;
            String tempString =null;
            while((tempString= reader.readLine())!=null){
                //System.out.println("line"+line+":"+tempString.split("\t").length);
                String[] tempArr = tempString.split("\t");
                if(tempArr.length!=15){
                    log.warn("Line length error!line "+line+":"+tempString);
                    continue;
                }
                String[] param = tempArr;
                String sql ="{call[test].[dbo].[test](?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}";
                CallableStatement call = con.prepareCall(sql);
                call.setString(1, param[0]);
                call.setString(2, param[1]);
                call.setString(3, param[2]);
                call.setString(4, param[3]);
                call.setString(5, param[4]);
                call.setString(6, param[5]);
                call.setString(7, param[6]);
                call.setString(8, param[7]);
                call.setString(9, param[8]);
                call.setString(10, param[9]);
                call.setString(11, param[10]);
                call.setString(12, param[11]);
                call.setString(13, param[12]);
                call.setString(14, param[13]);
                call.setString(15, param[14]);
                call.execute();
                line ++;
            }
            reader.close();
        }catch(Exception e){
            log.error(e.getMessage(), e);
        }finally{
            if(reader !=null){
                try{
                    reader.close();
                }catch(IOException e1){
                }
            }
            try{
                if(con !=null)
                    con.close();
            }catch(SQLException e){
            }
        }
    }

    publicstaticvoidreadAddReq(String path){
        BufferedReader reader =null;
        log.info("Read add request file:"+path);
        Connection con = getConnection();// 数据连接
        try{
            File file =newFile(path);
            reader =newBufferedReader(newFileReader(file));
            int line =1;
            String tempString =null;
            while((tempString= reader.readLine())!=null){
                //System.out.println("line"+line+":"+tempString.split("\t").length);

                String[] tempArr = tempString.split("\t");
                if(tempArr.length!=15){
                    log.warn("Line length error!line "+line+":"+tempString);
                    continue;
                }
                String[] param = tempArr;
                String sql ="{call[AndroidPlatform].[dbo].[pJTgdlt_ftp_add](?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}";
                CallableStatement call = con.prepareCall(sql);
                call.setString(1, param[0]);
                call.setString(2, param[1]);
                call.setString(3, param[2]);
                call.setString(4, param[3]);
                call.setString(5, param[4]);
                call.setString(6, param[5]);
                call.setString(7, param[6]);
                call.setString(8, param[7]);
                call.setString(9, param[8]);
                call.setString(10, param[9]);
                call.setString(11, param[10]);
                call.setString(12, param[11]);
                call.setString(13, param[12]);
                call.setString(14, param[13]);
                call.setString(15, param[14]);
                call.execute();
                line ++;
            }
            reader.close();
        }catch(Exception e){
            log.error(e.getMessage(), e);
        }finally{
            if(reader !=null){
                try{
                    reader.close();
                }catch(IOException e1){
                }
            }
        }
    }

    staticStringworkPath=null;

    publicstaticStringgetPropertiesValueByKey(String fileName,String key){
        Properties p =newProperties();
        String value ="";
        try{
            InputStream in =newBufferedInputStream(newFileInputStream(fileName));
            p.load(in);
            value = p.getProperty(key);
        }catch(Exception e){
            e.printStackTrace();
            return"";
        }
        return value;
    }

}
时间: 2024-10-14 14:49:49

java连接FTP、删除、下载文件的工具类的相关文章

java操作FTP,实现文件上传下载删除操作

上传文件到FTP服务器: /** * Description: 向FTP服务器上传文件 * @param url FTP服务器hostname * @param port FTP服务器端口,如果默认端口请写-1 * @param username FTP登录账号 * @param password FTP登录密码 * @param path FTP服务器保存目录 * @param filename 上传到FTP服务器上的文件名 * @param input 输入流 * @return 成功返回t

Linux命令-下载文件的工具:wget

Linux系统中的wget是一个下载文件的工具,它用在命令行下.对于Linux用户是必不可少的工具,我们经常要下载一些软件或从远程服务器恢复备份到本地服务器.wget支持HTTP,HTTPS和FTP协议,可以使用HTTP代理.所谓的自动下载是指,wget可以在用户退出系统的之后在后台执行.这意味这你可以登录系统,启动一个wget下载任务,然后退出系统,wget将在后台执行直到任务完成,相对于其它大部分浏览器在下载大量数据时需要用户一直的参与,这省去了极大的麻烦. wget 可 以跟踪HTML页面

C# 实现访问FTP服务器下载文件,获取文件夹信息小记

最近因为要开发广告制作工具,自动生成广告流,需要获取第三方服务器上的文件资源,经过摸索,从这次经历中记录下. FtpWebRequest reqFtp; WebResponse response = null; //获取文件夹信息 reqFtp = (FtpWebRequest)WebRequest.Create(this.ftp);//ftp://IP:port/文件夹名1/文件夹名2/.../文件夹名 reqFtp.UseBinary = true; reqFtp.KeepAlive = f

Android中使用Apache common ftp进行下载文件

在Android使用ftp下载资源 可以使用ftp4j组件,还可以用apache common net里面的ftp组件,这2个组件我都用过. 个人感觉Apache common net里面的组件比较好用一些,下面是一个实例. 项目中对ftp的使用进行了封装,添加了回调函数已经断点续传的方法. FTPCfg 用来存储ftp地址,密码等信息的. FTPClientProxy 只是个代理而已,里面主要封装了common ftp api IRetrieveListener做回调用的,比如用于是否下载完成

Java 压缩文件夹工具类(包含解压)

依赖jar <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.18</version> </dependency> CompressUtils.java package utils; import java.io.BufferedInputStream;

java文件处理工具类

import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileRea

通过cmd命令到ftp上下载文件

通过cmd命令到ftp上下载文件 点击"开始"菜单.然后输入"cmd"点"enter"键,出现cmd命令执行框 2 输入"ftp"切换到到ftp下面.然后输入"open 服务器地址".点击回车键.会提示你输入用户名和密码. 3 登陆成功后.输入"cd"命令.会显示"远程目录",输入"dir"命令会显示目录下的文件,权限等相关信息.可以通过"

文件夹工具类 - FolderUtils

文件夹工具类,提供创建完整路径的方法. 源码如下:(点击下载 -FolderUtils.java .commons-io-2.4.jar ) import java.io.File; import org.apache.commons.io.FilenameUtils; /** * 文件夹工具 * */ public class FolderUtils { /** * 创建完整路径 * * @param path * a {@link java.lang.String} object. */ p

list集合、txt文件对比的工具类和文件读写工具类

工作上经常会遇到处理大数据的问题,下面两个工具类,是在处理大数据时编写的:推荐的是使用map的方式处理两个list数据,如果遇到list相当大数据这个方法就起到了作用,当时处理了两个十万级的list,使用改方法的变种搞定. 1.txt文件.list集合比较工具 <span style="font-family:KaiTi_GB2312;font-size:18px;">package com.hudong.util.other; import java.util.Colle