码迷,mamicode.com
首页 > Web开发 > 详细

Quartz石英调度实现ftp文件上传

时间:2017-08-06 19:37:03      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:quartz   spring任务调度   quartz石英调度实现ftp文件上传   ftp文件上传   

Quartz石英调度实现ftp文件上传

实现一个每月1号00点01分自动生成的文件,通过ftp传到另一台主机上

1.先创建一个job任务类FtpUploadFileJobTask

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FtpUploadFileJobTask{
    private FTPClient ftpClient;
    
    /**
         * 实现任务的方法
         */
    public void execute() {
        
        String fileName = "xxx.avl";
        String username = "username";
        String password ="password";
        //目标主机IP
        String ip = "10.200.130.23";
        int port =21;
        //上传到主机的文件路径
        String remotepath="/xxxx/src/MHTOSTA/";
        try {
            //16进制01作为数据分隔符
            byte[] b1 = {0x01};
            String b1Str = new String(b1);
            StringBuffer sb = new StringBuffer();
            String titleStr = "用户ID"+b1Str+"订单生成时间"+b1Str+"月份"+b1Str+"代理商编码"+b1Str+"推荐工号"+"\r\n";
            sb.append(titleStr);
            //内容追加省略。。。
            boolean connetFlag= getConnetFTP(ip, port, username, password, remotepath, fileName);
            if(connetFlag){
                //上传数据文件
                uploadFile(remotepath, fileName, new ByteArrayInputStream((sb.toString()).getBytes("GBK")));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //关闭连接
            ftpLogOut();
        }
    }
    
    /**
     * ftp上传文件
     * @param path
     * @param filename
     * @param input
     * @return
     */
    public boolean uploadFile(
            String path, // FTP服务器保存目录
            String filename, // 上传到FTP服务器上的文件名
            InputStream input // 输入流
    ) {
        boolean isLogin = false;
        try {
            //创建目录,转移工作目录至指定目录下
            createDirs(path);
            isLogin = this.ftpClient.storeFile(filename, input);
            if (!isLogin) {
                this.ftpClient.disconnect();
                return isLogin;
            }
            isLogin = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (input != null)
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return isLogin;
    }
    /**
     * ftp链接
     *
     * @param hostname
     * @param port
     * @param username
     * @param password
     * @param path
     * @param filename
     * @return
     */
    public boolean getConnetFTP(String hostname,// FTP服务器hostname
            int port,// FTP服务器端口
            String username, // FTP登录账号
            String password, // FTP登录密码
            String path, // FTP服务器保存目录
            String filename // 上传到FTP服务器上的文件名
    ) throws IOException{
        boolean isLogin = false;
        this.ftpClient = new FTPClient();
        int reply;
        if (port > 0) {
            this.ftpClient.connect(hostname, port);// 连接FTP服务器
        } else {
            this.ftpClient.connect(hostname);
        }
        // 如果采用默认端口,可以使用ftp.connect(ftp)的方式直接连接FTP服务器
        this.ftpClient.login(username, password);// 登录
        // 检验是否连接成功
        reply = this.ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
                System.out.println("ftp链接失败>>>");
            this.ftpClient.disconnect();
            return isLogin;
        }
        //使用二进制保存方式,没有设置在linux系统下换行“\r\n”不起作用
        this.ftpClient.setFileType(this.ftpClient.BINARY_FILE_TYPE);
        isLogin = true;
        return isLogin;
    }
    /**
     * @退出关闭服务器链接
     * */
    public void ftpLogOut() {
        if (null != this.ftpClient && this.ftpClient.isConnected()) {
            try {
                boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
                if (reuslt) {
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(this.ftpClient.isConnected()){
                    try {
                        this.ftpClient.disconnect();// 关闭FTP服务器的连接
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    /**
     * 创建目录
     * @param remoteUpLoadPath
     * @throws IOException
     */
    public void createDirs(String remoteUpLoadPath) throws IOException {
        String[]dirs = remoteUpLoadPath.split("/");
        //移动到linux系统的根目录下,注:这段代码在window系统上执行代码会报错。
        this.ftpClient.changeWorkingDirectory("/");
        for(String dir : dirs){
            this.ftpClient.mkd(dir);
            this.ftpClient.changeWorkingDirectory(dir);
        }
    }
}


这里仅是通过ftp在目标主机上生产文件,并把数据直接写入生成的文件中。

如果需要在项目主机上先生成文件在通过ftp传到目标主机上,则可以通过以下代码实现:


先将数据写入文件:

/**
     * 数据写入到文件
     * @param content
     */
    public void writerFileDate(String content,String fileName,boolean writeflag){
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(fileName,writeflag)));
            bw.write(content);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(bw!=null){
                    bw.close();// 关闭输出流
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
/**
     * 创建文件路径,并获取文件名
     * @return
     */
    public String getCreateFile(String path,String fileName){
        File file = new File(path+fileName);
        if(!file.exists()){//文件不存在
            file.getParentFile().mkdirs();//创建文件目录
        }
        return path+fileName;
    }

调用写入数据方法

//context:数据内容
this.writerFileDate(context, this.getCreateFile(localpath,fileName),false);

生成文件后,在通过ftp传到目标主机,关键代码如下:

     FileInputStream in=null;
            try {
                in = new FileInputStream(new File(localpath + fileName));
                boolean uploadflag=uploadFile(ip, port, username,
                        password, remotepath,
                        fileName, in);
                if(uploadflag){
                    System.out.println("ftp上传文件成功>>>");
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

上传方法:

public boolean uploadFile(String hostname,// FTP服务器hostname
            int port,// FTP服务器端口
            String username, // FTP登录账号
            String password, // FTP登录密码
            String path, // FTP服务器保存目录
            String filename, // 上传到FTP服务器上的文件名
            InputStream input // 输入流
    ) {
        boolean isLogin = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            if (port > 0) {
                ftp.connect(hostname, port);// 连接FTP服务器
            } else {
                ftp.connect(hostname);//默认端口可以这样链接
            }
            // 如果采用默认端口,可以使用ftp.connect(ftp)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            // 检验是否连接成功
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return isLogin;
            }
            System.out.println("ftp链接成>>>>>>>>>>>>");
//            FTPFile[] files = ftp.listFiles();
//            for (FTPFile file : files) {
//                file.isFile();
//                file.getName();
//                file.getTimestamp();
//            }
            //创建目录,转移工作目录至指定目录下
            ftp = createDirs(path,ftp);
//            //转移工作目录至指定目录下
//            isLogin = ftp.changeWorkingDirectory(path);
//            log.info("pIsSuc:" + isLogin);
//            if (!isLogin) {
//                ftp.disconnect();
//                return isLogin;
//            }
            isLogin = ftp.storeFile(filename, input);
            if (!isLogin) {
                System.out.println("ftp上传文件失败:" + isLogin+">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                ftp.disconnect();
                return isLogin;
            }
            isLogin = true;
        } catch (FileNotFoundException e) {
        //后面代码省略。。。。


2.在applicationContext.xml中配置定时任务的时间,关键代码如下:

<!-- 定时生成报表文件 -->
   <bean id="ftpUploadFileJobTask" class="com.quartz.FtpUploadFileJobTask">
        <property name="testService">
            <ref bean="testService"/>
        </property>
    </bean>
    <bean id="ftpUploadFileJobBean"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="ftpUploadFileJobTask" />
        <property name="targetMethod" value="execute" />
    </bean>
    <bean id="ftpUploadFileQuartTime" class="org.springframework.scheduling.quartz.CronTriggerBean"
        lazy-init="false" autowire="no">
        <property name="jobDetail">
            <ref bean="ftpUploadFileJobBean" />
        </property>
        <!-- 0 1 0 1 * ?==0:秒,1:分,0:时,1:号,*:每个月,?星期几 -->
        <property name="cronExpression" value="0 1 0 1 * ?" /> <!-- 每月的1号的00点01分执行-->
    </bean>
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
            <ref bean="ftpUploadFileQuartTime"/>
            </list>
        </property>
    </bean>









本文出自 “10916470” 博客,转载请与作者联系!

Quartz石英调度实现ftp文件上传

标签:quartz   spring任务调度   quartz石英调度实现ftp文件上传   ftp文件上传   

原文地址:http://10926470.blog.51cto.com/10916470/1954022

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!