• java web--FTP服务器创建和上下传文件(3)


     1.FTP服务器上传和下载功能  查看详情  

                    1).首先在本地机器上创建一个用户!这些用户是用来登录到FTP的!我的电脑右键->管理->本地用户和组->用户->“右键”新建用户->输入用户名和密码再点创建就行了!

                   

                    2).其次是在C盘新建文件夹“FTP上传”和“FTP下载”两个文件夹!并在每个文件夹里放不同的文件,以便区分!

                   

                     3)   之后是安装IIS组件!在开始菜单里—>控制面板-〉添加或删除程序->添加/删除windows组件->应用程序服务器->Internet 信息服务->

                                -〉FTP服务器-〉确定-〉完成!这样就把FTP安装在服务器上了!

                     

                4)     最后就是配置FTP服务器,创建上传和下载服务!创建上传服务器:右键网站->选择添加FTP站点->描述可以根据自己的需要填写

                       ->地址一般都是自己的IP地址,端口默认使用21->物理路径指向“C:FTP上传”->访问权限要钩上“读取”和“写入”->点击完成就把上传的服务创建好了!

                注意:如果服务和应用程序下面  没有 internet信息服务(IIS)管理这一项 需要在打开和关闭windows功能添加  web管理工具全选   如图:

                     

                   上传服务器图解:

                      

                      

                       

          5)  创建下载服务器:因为21号端口已经被占用所以我们就用2121端口!它的物理路径指向“C:FTP下载”!只有读取权限!!具体的步骤和FTP上传一样,区别只是读取。

          6)最后就可以测试刚才建立的ftp服务器是否建立成功了。在IE浏览器上输入以下地址ftp://192.168.8.100即可打开具有上传功能的FTP页面,

              输入ftp://192.168.9.3:2121即可打开只有下载功能的页面了!当然,登录之 前还需要你输入开始建立的那个账号及密码

            

      2.FTP 实现上传下载功能

       所需要的jar包    commons.net.jar      log4j.jar

    package com.zhouwuji.list;
    
    public class Ftp {
           private String ipAddr;//ip地址
            
            private Integer port;//端口号
            
            private String userName;//用户名
            
            private String pwd;//密码
            
            private String path;//aaa路径
        
            public String getIpAddr() {
                return ipAddr;
            }
        
            public void setIpAddr(String ipAddr) {
                this.ipAddr = ipAddr;
            }
        
            public Integer getPort() {
                return port;
            }
        
            public void setPort(Integer port) {
                this.port = port;
            }
        
            public String getUserName() {
                return userName;
            }
        
            public void setUserName(String userName) {
                this.userName = userName;
            }
        
            public String getPwd() {
                return pwd;
            }
        
            public void setPwd(String pwd) {
                this.pwd = pwd;
            }
        
            public String getPath() {
                return path;
            }
        
            public void setPath(String path) {
                this.path = path;
            }
            
    }
    package com.zhouwuji.list;
    
    
    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.util.List;
    
    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);
         
        private static FTPClient ftp;
               
               /**
                * 获取ftp连接
                * @param f
                * @return
                * @throws Exception
                */
               public static boolean connectFtp(Ftp f) throws Exception{
                   ftp=new FTPClient();
                   boolean flag=false;
                   int reply;
                   if (f.getPort()==null) {
                       ftp.connect(f.getIpAddr(),21);
                   }else{
                       ftp.connect(f.getIpAddr(),f.getPort());
                   }
                   ftp.login(f.getUserName(), f.getPwd());
                   ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                   reply = ftp.getReplyCode();      
                   if (!FTPReply.isPositiveCompletion(reply)) {      
                         ftp.disconnect();      
                         return flag;      
                   }      
                   ftp.changeWorkingDirectory(f.getPath());      
                   flag = true;      
                   return flag;
               }
               
               /**
                * 关闭ftp连接
                */
               public static void closeFtp(){
                   if (ftp!=null && ftp.isConnected()) {
                       try {
                           ftp.logout();
                           ftp.disconnect();
                       } catch (IOException e) {
                           e.printStackTrace();
                       }
                   }
               }
               
               /**
                * ftp上传文件
                * @param f
                * @throws Exception
                */
               public static void upload(File f) throws Exception{
                   if (f.isDirectory()) {
                       ftp.makeDirectory(f.getName());
                       ftp.changeWorkingDirectory(f.getName());
                       String[] files=f.list();
                       for(String fstr : files){
                           File file1=new File(f.getPath()+"/"+fstr);
                           if (file1.isDirectory()) {
                               upload(file1);
                               ftp.changeToParentDirectory();
                           }else{
                               File file2=new File(f.getPath()+"/"+fstr);
                               FileInputStream input=new FileInputStream(file2);
                               ftp.storeFile(file2.getName(),input);
                               input.close();
                           }
                       }
                   }else{
                       File file2=new File(f.getPath());
                       FileInputStream input=new FileInputStream(file2);
                       ftp.storeFile(file2.getName(),input);
                       input.close();
                   }
               }
               
               /**
                * 下载链接配置
                * @param f
                * @param localBaseDir 本地目录
                * @param remoteBaseDir 远程目录
                * @throws Exception
                */
               public static void startDown(Ftp f,String localBaseDir,String remoteBaseDir ) throws Exception{
                   if (FtpUtil.connectFtp(f)) {
                       
                     try { 
                         FTPFile[] files = null; 
                         boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir); 
                         if (changedir) { 
                             ftp.setControlEncoding("GBK"); 
                             files = ftp.listFiles(); 
                             for (int i = 0; i < files.length; i++) { 
                                 try{ 
                                     downloadFile(files[i], localBaseDir, remoteBaseDir); 
                                 }catch(Exception e){ 
                                     logger.error(e); 
                                     logger.error("<"+files[i].getName()+">下载失败"); 
                                 } 
                             } 
                         } 
                     } catch (Exception e) { 
                         logger.error(e); 
                         logger.error("下载过程中出现异常"); 
                     } 
                 }else{
                     logger.error("链接失败!");
                 }
                 
             }
             
             
             /** 
              * 
              * 下载FTP文件 
              * 当你需要下载FTP文件的时候,调用此方法 
              * 根据<b>获取的文件名,本地地址,远程地址</b>进行下载 
              * 
              * @param ftpFile 
              * @param relativeLocalPath 
              * @param relativeRemotePath 
              */ 
             private  static void downloadFile(FTPFile ftpFile, String relativeLocalPath,String relativeRemotePath) { 
                 if (ftpFile.isFile()) {
                     if (ftpFile.getName().indexOf("?") == -1) { 
                         OutputStream outputStream = null; 
                         try { 
                             File locaFile= new File(relativeLocalPath+ ftpFile.getName()); 
                             //判断文件是否存在,存在则返回 
                             if(locaFile.exists()){ 
                                 return; 
                             }else{ 
                                 outputStream = new FileOutputStream(relativeLocalPath+ ftpFile.getName()); 
                                 ftp.retrieveFile(ftpFile.getName(), outputStream); 
                                 outputStream.flush(); 
                                 outputStream.close(); 
                             } 
                         } catch (Exception e) { 
                             logger.error(e);
                         } finally { 
                             try { 
                                 if (outputStream != null){ 
                                     outputStream.close(); 
                                 }
                             } catch (IOException e) { 
                                logger.error("输出文件流异常"); 
                             } 
                         } 
                     } 
                 } else { 
                     String newlocalRelatePath = relativeLocalPath + ftpFile.getName(); 
                     String newRemote = new String(relativeRemotePath+ ftpFile.getName().toString()); 
                     File fl = new File(newlocalRelatePath); 
                     if (!fl.exists()) { 
                         fl.mkdirs(); 
                     } 
                     try { 
                         newlocalRelatePath = newlocalRelatePath + '/'; 
                         newRemote = newRemote + "/"; 
                         String currentWorkDir = ftpFile.getName().toString(); 
                         boolean changedir = ftp.changeWorkingDirectory(currentWorkDir); 
                         if (changedir) { 
                             FTPFile[] files = null; 
                             files = ftp.listFiles(); 
                             for (int i = 0; i < files.length; i++) { 
                                 downloadFile(files[i], newlocalRelatePath, newRemote); 
                             } 
                         } 
                         if (changedir){
                             ftp.changeToParentDirectory(); 
                         } 
                     } catch (Exception e) { 
                         logger.error(e);
                     } 
                 } 
             } 
         
             public boolean removeFile(String ftpFileName) {  
                 boolean flag = false;  
             
                 try {  
                     ftpFileName = new String(ftpFileName.getBytes("GBK"),"iso-8859-1");  
                     flag = ftp.deleteFile(ftpFileName);  
                     return flag;  
                 } catch (IOException e) {  
                     e.printStackTrace();  
                     return false;  
                 }  
             }
             
              public static void test() throws IOException{
                /*   //新建文件夹
                  int  s=ftp.mkd("/bak");
                    // 查询目录
                  FTPFile[] file= ftp.listDirectories();
                 for (FTPFile ftpFile : file) {
                    System.out.println(ftpFile);
                }*/
                 //读取文件内容
            /*InputStream inputStream= ftp.retrieveFileStream("sendLogDetail_201801.txt");    
            BufferedReader br =new BufferedReader(
                    new InputStreamReader(
                        new BufferedInputStream(inputStream)));
            String info =null;
            while(null!=(info=br.readLine())){
                System.out.println(info);
            
            }*/
             OutputStream outputStream2=ftp.appendFileStream("sendLogDetail_201801.txt");
             //OutputStream outputStream=ftp.storeFileStream("/sendLogDetail_201801.txt");
             String str="ZHOUWU";
             byte[] bsw=str.getBytes();
             outputStream2.write(bsw);
             outputStream2.close();
              }
              
              
             public static void main(String[] args) throws Exception{  
                     Ftp f=new Ftp();
                     f.setIpAddr("192.168.8.100");
                     f.setUserName("OU");
                     f.setPwd("OU7758521");
                     FtpUtil.connectFtp(f);
                     FtpUtil.test();
                     
                     
                     // File file = new File("D:/xp/test/sendLogDetail_201801.txt");  
                     //把文件上传在ftp上
                     // FtpUtil.upload(file);
                     //下载ftp文件测试
                    /*  FtpUtil.startDown(f, "D:/xp/",  "/");
                      System.out.println("ok");*/
                   
                }  
             
         }

          

                                                       

  • 相关阅读:
    在redhat 6.6上安装Docker
    Linux操作系统各版本ISO镜像下载(包括oracle linux edhatcentosu
    UML时序图(Sequence Diagram)学习笔记
    eureka 和zookeeper 区别 优势【转】
    HttpClient实现远程调用
    Java 1.8 Stream 用例测试
    ZooKeeper下载安装(Windows版本)
    Java1.8新特性
    mysql大数据量表索引与非索引对比
    druid监控mysql程序
  • 原文地址:https://www.cnblogs.com/ou-pc/p/8274886.html
Copyright © 2020-2023  润新知