FTP上传和下载文件实例

声明:本文纯属个人随手笔记,如果对您有参考价值我十分开心,如果有存在错误,或者有更好的解决办法也麻烦您留言告诉我,大家共同成长,切勿恶言相。 欢迎加入资源共享QQ群:275343679,一起发现知识、了解知识、学习知识、分享知识。网站:www.itlantian.top 

=======================================================================

本文利用apache ftp工具实现文件的上传下载。具体如下:

1、下载相应的jar包

     commons-net-1.4.1.jar

2、实现代码如下:

package com.xxxx.common.utils;

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.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ftp上传下载工具类
 * @author song.zhang3@pactera.com (zhangsong)
 * @date 2017年12月29日
 * @version 1.0
 */
public final class FtpUtils {
    
     private static final Logger logger   = LoggerFactory.getLogger(FtpUtils.class);
   /**  
     * Description: 向FTP服务器上传文件  
     * @param host FTP服务器hostname  
     * @param port FTP服务器端口  
     * @param username FTP登录账号  
     * @param password FTP登录密码  
     * @param basePath FTP服务器基础目录 
     * @param filePath FTP服务器文件存放路径。例如分日期存放:/2017/12/29。文件的路径为basePath+filePath 
     * @param filename 上传到FTP服务器上的文件名  
     * @param input 输入流  
     * @return 成功返回true,否则返回false  
     */    
    public static boolean uploadFile(String host, String 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, Integer.valueOf(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)) {  
                            logger.info("ftp 创建文件失败!"+tempPath);
                            return result;  
                        } else {  
                            ftp.changeWorkingDirectory(tempPath);  
                        }  
                    }  
                }  
            }  
            //设置上传文件的类型为二进制类型  
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
            //上传文件  
            if (!ftp.storeFile(filename, input)) {  
                return result;  
            }  
            input.close();  
            ftp.logout();  
            result = true;  
        } catch (IOException e) {  
            e.printStackTrace();  
        } 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) {  
            e.printStackTrace();  
        } finally {  
            if (ftp.isConnected()) {  
                try {  
                    ftp.disconnect();  
                } catch (IOException ioe) {  
                }  
            }  
        }  
        return result;  
    }      
}  
    

3.实例代码: 

/**
 * 全量同步(库存数量不一致)
 * @param oldFileName
 * @param detailMap
 * @return
 */
@Override
public String stockDifferSendEmail(Map<String, List<StockDetail>> detailMap,Map<String, String> nameMap) {
    String FtpfilePath =null;
    // 头部
    String[] head = new String[]{"同步时间","同步文件名","SKU","前天剩余库存","当天同步库存","库存差异","差异比率%"};
    // 尾部
    String footerStr[] = new String[]{"合计","/","/","","","",""};

    List<ExcelBean> beanList = new ArrayList<ExcelBean>();
    Map<Long, Integer> paramMap = new HashMap<Long, Integer>();
    paramMap.put(0L, 0);

    Map<Integer, Integer> iskeyMap = new HashMap<Integer, Integer>();
    iskeyMap.put(0, 0);

    for (String d_key : detailMap.keySet()) {            
        //获取差异数据集合
        List<StockDetail> listSum = detailMap.get(d_key);                
        String categoryName=nameMap.get(d_key);
        int totalSize=listSum.size();
        int pageSize=60000;
        //当条数大于最大限制条数6W条时进行切割
            int totalPage=0;
            int startIndex=0;
            int endIndex=0;
            totalPage=totalSize/pageSize+(totalSize%pageSize>0?1:0);
            logger.info("totalPage {}",totalPage);
            for(int i=0;i<=totalPage;i++){                     
                startIndex=i*pageSize;
                endIndex=(i+1)*pageSize>totalSize?totalSize:(i+1)*pageSize;
                logger.info("page {} >> startIndex {} >> endIndex {}",i,startIndex,endIndex);
                List<StockDetail> list=listSum.subList(startIndex, endIndex);
                //分页创建表格
                createExcelList(Long.valueOf(i),head, footerStr,list,categoryName, beanList );
            }
    }
    try {
        File dic = new File(new File(System.getProperty("user.dir"),stockDifferPath).getAbsolutePath());
        if (!dic.exists()||!dic.isDirectory()) {
            if (dic.mkdirs()) {
                logger.info("创建目录" + dic.getAbsolutePath() + "成功!");

            } else {
                logger.info("创建目录" + dic.getAbsolutePath() + "失败!");

            }
        }
        //获取文件名和路径
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName ="StockDifferInfo_"+ formatter.format(new Date()) + ".xls";
        String filePath = dic.getAbsolutePath() + "\\" +fileName ;
        //生成xls文件
        FileOutputStream fos = new FileOutputStream(filePath);
        ExcelUtils.writeExcel(beanList, fos);
        //将文件上传FTP
        FileInputStream input=new FileInputStream( new File(filePath));                                      
        FtpUtils.uploadFile(ftpUrl, ftpPort,ftpUserName, ftpPassword, "/", stockDifferPath,fileName, input);
        //拼接FTP文件根路径
        FtpfilePath=stockDifferPath+"/"+fileName;
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return FtpfilePath;
}

/**
 * 分页创建表格
 * @param num
 * @param head
 * @param footerStr
 * @param list
 * @param categoryName
 * @param beanList
 * @return
 */
private boolean createExcelList(Long num, String[] head,String[] footerStr,List<StockDetail> list,String categoryName,List<ExcelBean> beanList ){
    
    ExcelBean eb = new ExcelBean();
    eb.setCategorySid(num);
    eb.setCategoryName(categoryName);
    eb.setCellNum(7);
    eb.setFixedCellNum(7);
    eb.setHead(head);
    
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String data[][] = new String[list.size()][];
    for (int i = 0; i < list.size(); i++) {
        StockDetail sd = list.get(i);
        data[i] = new String[7];
        data[i][0] = format.format(sd.getCreateTime());
        data[i][1] = sd.getObjectId();
        data[i][2] = sd.getGoodsSid() + "";
        data[i][3] = sd.getOranStockSum() + "";
        data[i][4] = sd.getCurrStockSum() + "";
        data[i][5] = (sd.getCurrStockSum() - sd.getOranStockSum()) + "";
        if (sd.getOranStockSum() != 0) {
            DecimalFormat df = new DecimalFormat("0.00");// 格式化小数
            data[i][6] = df.format((float) (sd.getCurrStockSum() - sd
                    .getOranStockSum()) / sd.getOranStockSum() * 100)
                    + "%";
        } else {
            data[i][6] = (sd.getCurrStockSum() - sd.getOranStockSum())
                    + "/" + sd.getOranStockSum();
        }
    }
    
    Map<Long, Integer> paramMap = new HashMap<Long, Integer>();
    paramMap.put(0L, 0);

    Map<Integer, Integer> iskeyMap = new HashMap<Integer, Integer>();
    iskeyMap.put(0, 0);
    
    Map<Integer, String[]> propValueNameMap = new HashMap<Integer, String[]>();
    propValueNameMap.put(0, data[0]);
    eb.setData(data);
    eb.setFooter(footerStr);
    eb.setTemplateType(1);// 0.普通、1.合计
    eb.setParamMap(paramMap);
    eb.setPropValueNameMap(propValueNameMap);
    eb.setIskeyMap(iskeyMap);
    beanList.add(eb);
    
    return true;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值