周期性上传文件到ftp服务端指定路径功能实现

版权声明:转载请注明出处及作者! https://blog.csdn.net/chenzhanhai/article/details/78035273

程序的功能

       该程序实现周期性的从本地指定路径中获取文件及列表,上传到指定的ftp服务器路径中,并在上传完成后删除本地路径中的文件。使用方法:把本文中java代码打包成ftpupload.jar,并添加jdk路径后,执行run.bat文件。

程序的文件列表及功能描述

编号 文件名 文件功能
1 run.bat 文件启动应用程序,执行以完成程序功能。
2 config.properties 描述了ftp服务器的ip、用户、密码、远程路径、本地路径、执行周期等参数。
3 log4j.properties 日志记录模块通用配置文件。
4 AppTask.java 周期执行的任务,从本地获取文件列表,上传到ftp指定目录下,并删除本地文件。
5 Scheduler.java 主程序,创建定时器并启动
6 FilePara.java 文件名参数对象,包含文件名、文件绝对路径等参数处理,在AppTask类中调用
7 FtpParameters.java ftp服务端参数类,调用ParaFileUtil从config.properties文件中获取参数并被AppTask使用
8 FileUtil.java 文件操作类,实现了文件夹创建、删除等操作
9 FtpUtil.java ftp服务器操作类,实现ftp上文件的上传及下载
10 ParaFileUtil.java 参数文件config.properties对应的工具类,用来读取参数文件

详细程序的文件内容如下

1.run.bat文件

SET JAVA=jre6\bin\java.exe
SET DEBUG=-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=2345

%JAVA% %DEBUG% -Xmx384m -classpath lib\commons-net-3.6.jar;lib\ftpupload.jar;lib\log4j.jar; sz.app.Scheduler

2.config.properties文件

ip=127.0.0.1
port=21
user=czh
pwd=czh123
basePath=/abc
localPath=d:/abc
timeInterval=2

3.log4j.properties

# Configure logging for testing: optionally with log file
#可以设置级别:debug>info>error
#debug:可以显式debug,info,error
#info:可以显式info,error
#error:可以显式error


log4j.rootLogger=debug,appender1
#log4j.rootLogger=info,appender1
#log4j.rootLogger=error,appender1


#输出到控制台
log4j.appender.appender1=org.apache.log4j.ConsoleAppender
#样式为TTCCLayout
log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout

4.AppTask.java

package sz.app;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


import org.apache.log4j.Logger;


import sz.bean.FilePara;
import sz.bean.FtpParameters;
import sz.util.FileUtil;
import sz.util.FtpUtil;


public class AppTask extends java.util.TimerTask{
    private static Logger logger = Logger.getLogger(AppTask.class);
    
    @Override
    public void run() {
        logger.info("start task.");
        new AppTask().doUpload();
        logger.info("task complete.");
    }
        
    private void doUpload() {
        FtpParameters ftpPara = new FtpParameters();
        List<String> fileNames = new ArrayList<String>();
        traverseFolder(ftpPara.getLocalPath(), fileNames);
        
        for(String fileName:fileNames) {
            FilePara filePara = new FilePara(fileName);
            upload2ftp(filePara);
        }
        
        logger.info("start clear dir.");
        FileUtil.clearDir(ftpPara.getLocalPath());
        logger.info("start clear complete.");
    }
    
    private void upload2ftp(FilePara filePara) {
        FtpParameters ftpPara = new FtpParameters();
        
        InputStream inputStream;
        try {
            inputStream = new FileInputStream(new File(filePara.getPath()));
            boolean result = FtpUtil.uploadFile(ftpPara.getIp(), 
                    ftpPara.getPort(),
                    ftpPara.getUser(),
                    ftpPara.getPwd(),
                    ftpPara.getBasePath(),
                    "", 
                    filePara.getFileName(),
                    inputStream); 
            if (!result) {
                System.out.println("upload error! file:" + filePara.getPath());
                logger.warn("upload error! file:" + filePara.getPath());
            }  
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
            logger.error("upload error! file:" + filePara.getPath(), e);
        }
    }
    
    private void traverseFolder(String path, List<String> fileNames) {

        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files.length == 0) {
                return;
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        logger.info("遍历文件夹:" + file2.getAbsolutePath());
                        traverseFolder(file2.getAbsolutePath(), fileNames);
                    } else {
                        fileNames.add(file2.getAbsolutePath());
                        logger.info("找到文件:" + file2.getAbsolutePath());
                    }
                }
            }
        } else {
            logger.warn("文件夹不存在:" + path);
        }
    }
}

5.Scheduler.java

package sz.app;

import java.util.Timer;
import sz.bean.FtpParameters;


public class Scheduler {


    public static void main(String[] args){ 
        FtpParameters ftpPara = new FtpParameters();   
        Timer timer = new Timer();     
        AppTask myTask1 = new AppTask();     
                
        timer.schedule(myTask1, 1000, ftpPara.getTimeInterval() * 1000 * 60); 
    }
}

6.FilePara.java

package sz.bean;


import java.io.File;


public class FilePara {
    private String path;
    private String fileName;
    public void setPath(String path) {
        this.path = path;
    }
    public String getPath() {
        return path;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    public String getFileName() {
        return fileName;
    }
    
    public FilePara(String fileAbsoluteName) {
        File file = new File(fileAbsoluteName);
        setPath(fileAbsoluteName);
        setFileName(file.getName());
    }
}

7.FtpParameters.java

package sz.bean;


import sz.util.ParaFileUtil;


public class FtpParameters {
    private String ip;
    private int port;
    private String user;
    private String pwd;
    private String basePath;
    private String localPath;
    private int timeInterval;
    
    public void setIp(String ip) {
        this.ip = ip;
    }
    public String getIp() {
        return ip;
    }
    public void setPort(String port) {
        this.port = Integer.parseInt(port);
    }
    public int getPort() {
        return port;
    }
    public void setUser(String user) {
        this.user = user;
    }
    public String getUser() {
        return user;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public String getPwd() {
        return pwd;
    }
    
    public FtpParameters(){
        
        setIp(ParaFileUtil.getPropertyValue("ip"));
        setPort(ParaFileUtil.getPropertyValue("port"));
        setUser(ParaFileUtil.getPropertyValue("user"));
        setPwd(ParaFileUtil.getPropertyValue("pwd"));
        setBasePath(ParaFileUtil.getPropertyValue("basePath"));
        setLocalPath(ParaFileUtil.getPropertyValue("localPath"));
        setTimeInterval(ParaFileUtil.getPropertyValue("timeInterval"));
    }
    
    public static void main(String[] args) {
        FtpParameters ftpParameters = new FtpParameters();
        System.out.println(ftpParameters.getBasePath());
    }
    
    public void setBasePath(String basePath) {
        this.basePath = basePath;
    }
    
    public String getBasePath() {
        return basePath;
    }
    
    public void setLocalPath(String localPath) {
        this.localPath = localPath;
    }
    
    public String getLocalPath() {
        return localPath;
    }
    
    public void setTimeInterval(String timeInterval) {
        this.timeInterval = Integer.parseInt(timeInterval);
    }
    
    public int getTimeInterval() {
        return timeInterval;
    }
}

8.FileUtil.java

package sz.util;

import java.io.File;
import org.apache.log4j.Logger;



public class FileUtil {
    private static Logger logger = Logger.getLogger(FileUtil.class);
    
    public static boolean delete(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            logger.warn("删除文件失败:" + fileName + "不存在!");
            System.out.println("删除文件失败:" + fileName + "不存在!");
            return false;
        } else {
            if (file.isFile())
                return deleteFile(fileName);
            else
                return deleteDirectory(fileName);
        }
    }

    /**
     * 删除单个文件
     *
     * @param fileName
     *            要删除的文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                logger.info("删除单个文件" + fileName + "成功!");
                return true;
            } else {
                logger.warn("删除单个文件" + fileName + "失败!");
                System.out.println("删除单个文件" + fileName + "失败!");
                return false;
            }
        } else {
            logger.warn("删除单个文件失败:" + fileName + "不存在!");
            System.out.println("删除单个文件失败:" + fileName + "不存在!");
            return false;
        }
    }

    public static boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾,自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在,或者不是一个目录,则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            logger.warn("删除目录失败:" + dir + "不存在!");
            System.out.println("删除目录失败:" + dir + "不存在!");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = FileUtil.deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
            // 删除子目录
            else if (files[i].isDirectory()) {
                flag = FileUtil.deleteDirectory(files[i]
                        .getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            System.out.println("删除目录失败!");
            logger.warn("删除目录失败!");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            logger.info("删除目录" + dir + "成功!");
            return true;
        } else {
            return false;
        }
    }

    // 创建目录
    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {// 判断目录是否存在
            logger.warn("创建目录失败,目标目录已存在!");
            System.out.println("创建目录失败,目标目录已存在!");
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
            destDirName = destDirName + File.separator;
        }
        if (dir.mkdirs()) {// 创建目标目录
            logger.info("创建目录成功!" + destDirName);
            return true;
        } else {
            logger.warn("创建目录失败!");
            System.out.println("创建目录失败!");
            return false;
        }
    }

    public static void clearDir(String dir) {
        FileUtil.delete(dir);
        FileUtil.createDir(dir);
    }
}

9.FtpUtil.java

package sz.util;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


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


public class FtpUtil {
    private static Logger logger = Logger.getLogger(FtpUtil.class);
    
    public static boolean uploadFile(String host, int port, String username, String password, String basePath,
            String filePath, String filename, InputStream input) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);// 连接FTP服务器
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            //切换到上传目录
            if (!ftp.changeWorkingDirectory(basePath + filePath)) {
                //如果目录不存在创建目录
                String[] dirs = filePath.split("/");
                String tempPath = basePath;
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) continue;
                    tempPath += "/" + dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {
                        if (!ftp.makeDirectory(tempPath)) {
                            return result;
                        } else {
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            
            //设置上传文件的类型为二进制类型 .BINARY_FILE_TYPE
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
            //上传文件
            if (!ftp.storeFile(filename, input)) {
                return result;
            }
            input.close();
            ftp.logout();
            result = true;
        } catch (IOException e) {
            System.out.println(e.getMessage());
            logger.error("uploadFile error!", e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }
    
    /** 
     * Description: 从FTP服务器下载文件 
     * @param host FTP服务器hostname 
     * @param port FTP服务器端口 
     * @param username FTP登录账号 
     * @param password FTP登录密码 
     * @param remotePath FTP服务器上的相对路径 
     * @param fileName 要下载的文件名 
     * @param localPath 下载后保存到本地的路径 
     * @return 
     */  
    public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
            String fileName, String localPath) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File(localPath + "/" + ff.getName());


                    OutputStream is = new FileOutputStream(localFile);
                    ftp.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }


            ftp.logout();
            result = true;
        } catch (IOException e) {
            logger.error("downloadFile error!", e);
            System.out.println(e.getMessage());
             
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }
}

10.ParaFileUtil.java

package sz.util;


import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream; 
import java.util.Iterator;
import java.util.Properties;
import org.apache.log4j.Logger;


public class ParaFileUtil {
    private static Logger logger = Logger.getLogger(ParaFileUtil.class);
    static String paraFileName = "config.properties";

    public static String getPropertyValue(String fieldName) {
        String propertyValue = "";

        Properties prop = new Properties();
        try {

            InputStream in = new BufferedInputStream(new FileInputStream(paraFileName));
            prop.load(in);
            Iterator<String> it = prop.stringPropertyNames().iterator();
            while (it.hasNext()) {
                String key = it.next();
                if (fieldName.contentEquals(key)) {
                    propertyValue = prop.getProperty(key);
                }
            }
            in.close();
        } catch (Exception e) {
            System.out.println(e);
            logger.error("get property value error.", e);
        }

        return propertyValue;
    }
}

如果您喜欢我的文章,别忘了点赞和留言哦!

猜你喜欢

转载自blog.csdn.net/chenzhanhai/article/details/78035273