这里使用Apache的FTP jar 包

没有使用Java自带的FTPjar包

 

 工具类

 

package com.zit.ftp;

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.net.SocketException;
import java.util.Properties;

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;

import com.zit.adapter.camera.CameraListener;


public class FTPUtil {

    private static Logger logger = Logger.getLogger(FTPUtil.class);
    
    private static String classPath=CameraListener.class.getResource("/").getPath();
    private static String filesPath = classPath.substring(0, classPath.indexOf("WEB-INF")) + "file" ;
    
    private FTPClient ftpClient;
    //从本地文件获取各种属性
    private static String ftpIP=FTPConfig.getFTPHost();
    private static Integer ftpPort=Integer.valueOf(FTPConfig.getFTPPort());
    private static String ftpUserName=FTPConfig.getUserName();
    private static String ftpPassword=FTPConfig.getPassword();
    private static String ftpEncode = FTPConfig.getFTPEncode();
    private static String localPath=FTPConfig.getLocalFilePath();
    
    public FTPUtil() {
        
    }
    
    public synchronized boolean connectServer() {
        ftpClient = new FTPClient();
        ftpClient.setControlEncoding(ftpEncode);//解决上传文件时文件名乱码
        int reply = 0 ;
        try {
            // 连接至服务器
            ftpClient.connect(ftpIP,ftpPort);
            // 登录服务器
            ftpClient.login(ftpUserName, ftpPassword);
            //登陆成功,返回码是230
            reply = ftpClient.getReplyCode();
            // 判断返回码是否合法
            if(!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return false;
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return true;
    }
    
    //判断ftp服务器文件是否存在    
    public boolean existFile(String path)  {
        boolean flag = false;
        FTPFile[] ftpFileArr;
        try {
            ftpFileArr = ftpClient.listFiles(path);
            if (ftpFileArr.length > 0) {
                flag = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }
    
    //删除ftp文件
    public synchronized boolean deleteFile(String pathname, String filename){ 
        boolean flag = false; 
        try { 
            System.out.println("开始删除文件");
            //切换FTP目录 
            ftpClient.changeWorkingDirectory(pathname); 
            ftpClient.dele(filename); 
            ftpClient.logout();
            flag = true; 
            System.out.println("删除文件成功");
        } catch (Exception e) { 
            System.out.println("删除文件失败");
            e.printStackTrace(); 
        } finally {
            if(ftpClient.isConnected()){ 
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            } 
        }
        return flag; 
    }
    
    //从FTP server下载到本地文件夹
    public synchronized boolean download(String path){
        boolean flag = false;
        FTPFile[] fs=null;
        try {
            fs = ftpClient.listFiles("aaa");
            if(fs.length<0) {
                return flag;
            }
            //1、遍历FTP路径下所有文件
            for(FTPFile file:fs){
                
//                File localFile = new File(localPath+"/"+file.getName());
                //2、保存到本地
                OutputStream os = new FileOutputStream(localFile);
                //retrieveFile(FTP服务端的源路径),这个路径要和listFiles的路径一致
                ftpClient.retrieveFile("aaa/" + file.getName(), os);
                //3、删除FTP中的上面保存的文件
                //循环外关闭,读一个关闭一次挺慢的
                is.flush();
                is.close();
            }
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
        }  
        return flag;
    }

    
    
    
    public synchronized boolean upload(InputStream inputStream , String fileName , String path) {
        try {
             
            //切换工作路径,设置上传的路径 
            ftpClient.changeWorkingDirectory(path);
            //设置1M缓冲
             ftpClient.setBufferSize(1024);
             // 设置被动模式
             ftpClient.enterLocalPassiveMode();
             // 设置以二进制方式传输
             ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
             /*
              * 第一个参数:服务器端文档名 
              * 第二个参数:上传文档的inputStream 
              * 在前面设置好路径,缓冲,编码,文件类型后,开始上传
              */
             ftpClient.storeFile(fileName, inputStream);
            inputStream.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            closeClient();
        }
         
    }
    
    public boolean checkSubfolder(String path, String subfolderName) {
        try {
            //切换到FTP根目录
            ftpClient.changeWorkingDirectory(path);
            //查看根目录下是否存在该文件夹
            InputStream is = ftpClient.retrieveFileStream(new String(subfolderName.getBytes("UTF-8")));
            if (is == null || ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE) {
                //若不存在该文件夹,则创建文件夹
                return createSubfolder(path,subfolderName);
            }
            if (is != null) {
                is.close();
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch(Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    
    public synchronized boolean createSubfolder(String path,String subfolderName){
        try {
            ftpClient.changeWorkingDirectory(path);
            ftpClient.makeDirectory(subfolderName);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
    
    
    /**
     * 断开与远程服务器的连接
     */
    public void closeClient(){
        if (ftpClient != null && ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
    
}

 

 

测试类:

package com.zit.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import com.zit.util.FTPUtil;

public class TestFTP {

    public static void main(String[] args) {
        
        FTPUtil ftpClient = new FTPUtil();
        ftpClient.connectServer();
        
        try {
            File file = new File("D:\\test.doc");
            InputStream stream = new FileInputStream(file);
            String ftpPath = "D:\\FTP";
            String fileName = "文件夹";
            boolean b = ftpClient.checkSubfolder(ftpPath, fileName);
            if(stream != null && b) {
                ftpClient.upload(stream, "aaa.doc", fileName);
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        
        
        
    }
}

 

实验工具:

filezilla server(FTP服务端工具)

官网下载即可

 

步骤

点击左上角小头像

1、Add新增用户,输入用户名

2、输入密码

3、Share folders 共享文件夹,就是设置FTP根目录

4、Add选择共享文件夹,在本地某文件夹即可

5、勾选该文件夹用户的权限,都选上

6、点击OK即可

 

 

 

 

 

 

实验结果:

运行测试类,即可看到,我已经把某个文档,上传到FTP根目录下了

 

 posted on 2018-09-06 10:38  布鲁布鲁sky  阅读(11605)  评论(0编辑  收藏  举报