zoukankan      html  css  js  c++  java
  • Java实现FTP上传下载功能

    http://lavasoft.blog.51cto.com/62575/93883/

    Java FTP客户端工具包很多,在此我选用的Apache的FTPClient。这个包的获取可以通过[url]http://commons.apache.org/net/[/url]来获取,我使用的是最新的commons-net-1.4.1.zip。其中包含了众多的java网络编程的工具包,官方文档列举如下:
        支持网络协议如下: 
            FTP 
            NNTP 
            SMTP 
            POP3 
            Telnet 
            TFTP 
            Finger 
            Whois 
            rexec/rcmd/rlogin 
            Time (rdate) and Daytime 
            Echo 
            Discard 
            NTP/SNTP

    都很有用。在此我用到的是FTP相关的一些包。
    public class FtpTest { 
        public static void main(String[] args) { 
            testUpload(); 
            testDownload(); 
        } 
    
        /** 
         * FTP上传单个文件测试 
         */ 
        public static void testUpload() { 
            FTPClient ftpClient = new FTPClient(); 
            FileInputStream fis = null; 
    
            try { 
                ftpClient.connect("192.168.14.117"); 
                ftpClient.login("admin", "123"); 
    
                File srcFile = new File("C:\new.gif"); 
                fis = new FileInputStream(srcFile); 
                //设置上传目录 
                ftpClient.changeWorkingDirectory("/admin/pic"); 
                ftpClient.setBufferSize(1024); 
                ftpClient.setControlEncoding("GBK"); 
                //设置文件类型(二进制) 
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); 
                ftpClient.storeFile("3.gif", fis); 
            } catch (IOException e) { 
                e.printStackTrace(); 
                throw new RuntimeException("FTP客户端出错!", e); 
            } finally { 
                IOUtils.closeQuietly(fis); 
                try { 
                    ftpClient.disconnect(); 
                } catch (IOException e) { 
                    e.printStackTrace(); 
                    throw new RuntimeException("关闭FTP连接发生异常!", e); 
                } 
            } 
        } 
    
        /** 
         * FTP下载单个文件测试 
         */ 
        public static void testDownload() { 
            FTPClient ftpClient = new FTPClient(); 
            FileOutputStream fos = null; 
    
            try { 
                ftpClient.connect("192.168.14.117"); 
                ftpClient.login("admin", "123"); 
    
                String remoteFileName = "/admin/pic/3.gif"; 
                fos = new FileOutputStream("c:/down.gif"); 
    
                ftpClient.setBufferSize(1024); 
                //设置文件类型(二进制) 
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); 
                ftpClient.retrieveFile(remoteFileName, fos); 
            } catch (IOException e) { 
                e.printStackTrace(); 
                throw new RuntimeException("FTP客户端出错!", e); 
            } finally { 
                IOUtils.closeQuietly(fos); 
                try { 
                    ftpClient.disconnect(); 
                } catch (IOException e) { 
                    e.printStackTrace(); 
                    throw new RuntimeException("关闭FTP连接发生异常!", e); 
                } 
            } 
        } 
    } 
    public class Ftp {
        private static final Logger logger = Logger.getLogger(FTP.class);
        /**
         * FTP客户端
         */
        private FtpClient ftpClient;
    
        /**
         * 服务器连接
         * 
         * @param ip
         *            服务器IP
         * @param port
         *            服务器端口
         * @param user
         *            用户名
         * @param password
         *            密码
         * @param path
         *            服务器路径
         * @throws IOException
         * 
         */
        public void connectServer(String ip, int port, String user, String password, String path) throws IOException {
            try {
                System.out.println("ftp connect...");
                ftpClient = new FtpClient(ip);
                ftpClient.login(user, password);
                // 设置成2进制传输
                ftpClient.binary();
                System.out.println("ftp login success!");
                if (path.length() != 0) {
                    // 把远程系统上的目录切换到参数path所指定的目录
                    try {
                        ftpClient.cd(path);
                    } catch (Exception e) {
                        throw new IOException("FTP server: 550 CWD failed 远程目录未响应", e);
                    }
                }
                ftpClient.binary();
            } catch (IOException e) {
                logger.error("ftp connect err!");
                logger.error(e.getMessage());
                e.printStackTrace();
                throw new IOException(e.getMessage());
            }
        }
    
        /**
         * 关闭连接
         * 
         * 
         */
        public void closeConnect() {
            try {
                ftpClient.closeServer();
                System.out.println("closeConnect success");
            } catch (IOException ex) {
                System.out.println("not closeConnect");
                ex.printStackTrace();
                throw new RuntimeException(ex);
            }
        }
    
        /**
         * 上传文件
         * 
         * @param localFile
         *            本地文件
         * @param remoteFile
         *            远程文件
         * 
         */
        public void upload(String localFile, String remoteFile) {
            TelnetOutputStream os = null;
            FileInputStream is = null;
            try {
                // 将远程文件加入输出流中
                os = ftpClient.put(remoteFile);
                // 获取本地文件的输入流
                File file_in = new File(localFile);
                is = new FileInputStream(file_in);
                // 创建一个缓冲区
                byte[] bytes = new byte[1024];
                int c;
                while ((c = is.read(bytes)) != -1) {
                    os.write(bytes, 0, c);
                }
                System.out.println("upload success");
            } catch (IOException ex) {
                System.out.println("not upload");
                ex.printStackTrace();
                throw new RuntimeException(ex);
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (os != null) {
                            os.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        /**
         * 下载文件
         * 
         * @param remoteFile
         *            远程文件路径(服务器端)
         * @param localFile
         *            本地文件路径(客户端)
         * 
         */
        public void download(String remoteFile, String localFile) {
            TelnetInputStream is = null;
            FileOutputStream os = null;
            try {
    
                // 获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
                is = ftpClient.get(remoteFile);
                File file_in = new File(localFile);
                os = new FileOutputStream(file_in);
                byte[] bytes = new byte[1024];
                int c;
                while ((c = is.read(bytes)) != -1) {
                    os.write(bytes, 0, c);
                }
                System.out.println("download success");
            } catch (IOException ex) {
                System.out.println("not download");
                ex.printStackTrace();
                throw new RuntimeException(ex);
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (os != null) {
                            os.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        /**
         * 返回FTP目录下的文件列表
         * 
         * @param ftpDirectory
         * @return
         */
        public List<String> getFileNameList(String ftpDirectory) {
            List<String> list = new ArrayList<String>();
            BufferedReader bf = null;
            InputStreamReader isr = null;
            DataInputStream ds = null;
            try {
                ds = new DataInputStream(ftpClient.nameList(ftpDirectory));
                isr = new InputStreamReader(ds);
                bf = new BufferedReader(isr);
                String filename = "";
                while ((filename = bf.readLine()) != null) {
                    list.add(filename);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    ds.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    bf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return list;
        }
    
        public static void main(String agrs[]) throws Exception {
    
            Ftp ftp = new Ftp();
            ftp.connectServer("192.168.1.221", 21, "admin", "123@123", "/FTP Files/temp");
    
            List<String> list = ftp.getFileNameList("/FTP Files/temp");
            for (String str : list) {
                try {
                    Calendar cal = Calendar.getInstance();// 使用日历类
                    int year = cal.get(Calendar.YEAR);// 得到年
                    int month = cal.get(Calendar.MONTH) + 1;// 得到月,因为从0开始的,所以要加1
                    int day = cal.get(Calendar.DAY_OF_MONTH);// 得到天
                    String fileName = "WiMAX_" + year + month + day;
                    System.out.println("str" + str + "---------" + "fileName:" + fileName);
    
                    String regEx = "WiMAX_\d{8}_\d{5}_\s{5}"; // 表示a或F
                    Pattern pat = Pattern.compile(regEx);
                    System.out.println(pat.matcher(str).find());
    
                    // if (str.contains(fileName)) {
                    // fu.download("/FTP Files/temp/" + str, "d:/temp/" + str);
                    // System.out.println("download:" + str);
                    // }
    
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error(e.getMessage());
                    throw e;
                }
            }
    
    
            ftp.closeConnect();
        }
    }
    View Code
  • 相关阅读:
    iOS __weak学习碰到的疑问
    Shiro整合SSH开发3:配置Shiro认证后页面地址跳转问题(和详述不配置须要注意的问题)
    Android Hawk数据库 github开源项目
    2015小米暑期实习笔试题_风口的猪-中国牛市(dp)
    opencv源代码之中的一个:cvboost.cpp
    regAsm的历史问题
    Spark核心概念理解
    linux的fork()函数具体解释 子进程复制父进程什么
    java8 Optional使用总结
    maven 项目报错org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)解决
  • 原文地址:https://www.cnblogs.com/lbangel/p/3424832.html
Copyright © 2011-2022 走看看