首页>代码>SMB协议、FTP协议方式下载及删除远程服务器文件>/src/main/java/com/voicecyber/thailandsubway/ftp/FtpTest.java
package com.voicecyber.thailandsubway.ftp;

import com.voicecyber.thailandsubway.utils.ApplicationConstants;
import com.voicecyber.thailandsubway.utils.SystemConfig;
import com.voicecyber.thailandsubway.utils.XmlUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/**
 * @Author: YafengLiang
 * @Description:  eTRA 东方通讯录音服务器
 * @Date: Created in  16:40 2018/12/5
 */
public class FtpTest {
    private static final Logger logger = LoggerFactory.getLogger(FtpTest.class);
    static FTPClient ftpClient;

    public static void main(String[] args) throws IOException {
        String rootFile = SystemConfig.FileLocation.baseLocation+ ApplicationConstants.FileName.THAILAND_SUBWAY;
        Element rootElement = XmlUtils.getRootNode(rootFile);
        List<Element> list = XmlUtils.getChildElements(rootElement,"ftp");
        String id1 = "1";
        if (list.size()>0){
            for (Element element : list) {
                String ids = element.attributeValue("id");
                if (id1.equals(ids)){
                    String HOST = element.attributeValue("ip");
                    int PORT = Integer.valueOf(element.attributeValue("port"));
                    String USERNAME = element.attributeValue("username");
                    String PASSWORD = element.attributeValue("password");
                    login(HOST,PORT,USERNAME,PASSWORD);

                    MyRun myRun = new MyRun();
                    new Thread(myRun).start();
                }
            }
        }

    }

    /**
     * 登录
      * @throws IOException
     */
    static void login(String HOST,int PORT,String USERNAME,String PASSWORD) throws IOException {
        ftpClient = new FTPClient();
        ftpClient.connect(HOST, PORT);
        ftpClient.login(USERNAME, PASSWORD);
        logger.info("登录成功");
        //设置编码
        ftpClient.setControlEncoding("UTF-8");
        ftpClient.setBufferSize(8096);
    }

    /**
     * 判断给定的路径是文件还是文件夹
     *
     * @param path
     * @return
     * @throws IOException
     */
    static boolean isDirectory(String path) throws IOException {
        //如果是文件,就会返回false
        //如果文件夹或文件名中含有中文,这里要转换一下,不然会返回false
        return ftpClient.changeWorkingDirectory(new String(path.getBytes(), "UTF-8"));
    }

    /**
     * 判断本地路径是否存在,不存在就创建路径
     *
     * @param path
     */
    static void makeDirs(String path) {
        String rootFile = SystemConfig.FileLocation.baseLocation+ ApplicationConstants.FileName.THAILAND_SUBWAY;
        Element rootElement = XmlUtils.getRootNode(rootFile);
        List<Element> list = XmlUtils.getChildElements(rootElement,"ftp");
        String id1 = "1";
        if (list.size()>0){
            for (Element element : list) {
                String ids = element.attributeValue("id");
                if (id1.equals(ids)){
                    String LOCAL_DIRECTORY = element.attributeValue("localPath");
                    File localFile = new File(LOCAL_DIRECTORY + path);
                    if (!localFile.exists()) {
                        localFile.mkdirs();
                        logger.info("名称:"+localFile+"目录已创建完成");
                    }
                }
            }
        }

    }

    /**
     * 下载单个文件
     *
     * @param dir
     * @throws IOException
     */
    static void downloadFile(String dir) throws IOException {
        String rootFile = SystemConfig.FileLocation.baseLocation+ ApplicationConstants.FileName.THAILAND_SUBWAY;
        Element rootElement = XmlUtils.getRootNode(rootFile);
        List<Element> list = XmlUtils.getChildElements(rootElement,"ftp");
        String id1 = "1";
        if (list.size()>0){
            for (Element element : list) {
                String ids = element.attributeValue("id");
                if (id1.equals(ids)){
                    String LOCAL_DIRECTORY = element.attributeValue("localPath");
                    File file = new File(LOCAL_DIRECTORY + dir);
                    OutputStream os = new FileOutputStream(file);
                    ftpClient.setControlEncoding("GBK");
                    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                    //如果文件名中含有中文,retrieveFile文件时会找不到FTP上的文件,导致保存在本地的是一个空文件,所以也要转换一下
                    ftpClient.retrieveFile(new String(file.getName().getBytes(), "UTF-8"), os);
                    logger.info("下载 "+file.getName()+" 完成");
                    os.close();
                }
            }
        }

    }

    /**
     * 下载任务,递归调用,循环下载所有目录下的文件
     *
     * @param path
     * @throws IOException
     */
    static void doDownload(String path) throws IOException {
        //创建本地目录
        makeDirs(path);
        //切换工作目录
        ftpClient.changeWorkingDirectory(new String(path.getBytes(), "UTF-8"));
        //获取目录下的文件列表
        String[] fileNames = ftpClient.listNames();
        //循环下载FTP目录下的文件
        for (String fname : fileNames) {
            if (isDirectory(path + "/" + fname)) {
                //递归调用
                doDownload(path + "/" + fname);
            } else {
                //下载单个文件
                downloadFile(path + "/" + fname);

                ftpClient.deleteFile(path + "/" + fname);
                logger.info("删除:"+fname+" 成功");
            }
        }
    }

    /**
     * 实时同步ftp目录文件到本地
     */
    public static class MyRun implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    logger.info("十秒后开始。。。。。。");
                    Thread.sleep(10 * 1000);
                    logger.info("继续。。。。。。");
                    doDownload("/");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }


    /**
     * FTP上传文件
     */

    public static void testUpload() {
        FTPClient ftpClient = new FTPClient();
        FileInputStream fis = null;

        try {
            ftpClient.connect("172.20.16.76", 9500);
            ftpClient.login("lyc", "123456");

            JFileChooser fd = new JFileChooser();
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            } catch (Exception e) {
                e.printStackTrace();
            }
            SwingUtilities.updateComponentTreeUI(fd);
            fd.showOpenDialog(null);
            File srcFile = fd.getSelectedFile();
            //if(srcFile != null){}

            fis = new FileInputStream(srcFile);
            //设置上传目录
            ftpClient.changeWorkingDirectory("/img");
            //ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding("GBK");
            //设置文件类型(二进制)
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.storeFile(srcFile.getName(), fis);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("FTP客户端出错!", e);
        } finally {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("关闭FTP连接发生异常!", e);
            }
        }
    }

}

最近下载更多
598381336  LV1 2024年3月29日
一蓑烟雨  LV11 2021年4月2日
lironggang  LV38 2021年2月5日
guaixia163  LV13 2020年11月11日
ChenTong_ZuiDaiMa  LV2 2020年10月2日
lyd19931203  LV21 2020年6月2日
15838634741  LV18 2020年4月2日
qq652133917  LV1 2020年1月11日
寒江无月  LV1 2019年11月7日
南风你好吗  LV5 2019年9月30日
最近浏览更多
598381336  LV1 2024年3月29日
itcaizhe  LV9 2022年4月28日
liys1234  LV9 2022年4月27日
18056615008  LV6 2021年12月7日
十月*  LV1 2021年10月11日
꧁* ¹꧂ꦿএ  LV1 2021年8月12日
aihui523  LV34 2021年8月5日
lilinfeng  LV1 2021年5月25日
zeng123222  LV1 2021年4月23日
一蓑烟雨  LV11 2021年4月2日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友