从ftp上传下载文件(二)

简介: ftp工具类,供文章(一)中类调用 import java.io.File; import java.io.FileInputStream; import java.

ftp工具类,供文章(一)中类调用

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FtpKit {
 
 public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) { 
     boolean success = false; 
     FTPClient ftp = new FTPClient(); 
     try { 
         int reply; 
         ftp.setConnectTimeout(2000);
         ftp.connect(url, port);//连接FTP服务器  
         //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器  
         ftp.login(username, password);//登录 
         ftp.setBufferSize(1024);
         ftp.setControlEncoding("UTF-8");
         ftp.setFileType(FTP.BINARY_FILE_TYPE);
         ftp.enterLocalActiveMode();
         ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
         reply = ftp.getReplyCode(); 
         if (!FTPReply.isPositiveCompletion(reply)) { 
             ftp.disconnect(); 
             return success; 
         } 
         ftp.changeWorkingDirectory(path); 
         success=ftp.storeFile(filename, input);          
         ftp.logout(); 
     } catch (IOException e) { 
         e.printStackTrace(); 
     } finally { 
         if (ftp.isConnected()) { 
             try { 
                 ftp.disconnect(); 
             } catch (IOException ioe) { 
             } 
         }
     } 
     return success; 
 }
 
 private FTPClient ftpClient; 
    public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE
    public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE
     
    /**
     * 利用FtpConfig进行服务器连接
     * @param ftpConfig 参数配置Bean类
     * @throws SocketException
     * @throws IOException
     */
    public void connectServer(FtpConfig ftpConfig) throws SocketException, 
            IOException { 
        String server = ftpConfig.getServer(); 
        int port = ftpConfig.getPort(); 
        String user = ftpConfig.getUsername(); 
        String password = ftpConfig.getPassword(); 
        String location = ftpConfig.getLocation(); 
        connectServer(server, port, user, password, location); 
    } 
     
    /**
     * 使用详细信息进行服务器连接
     * @param server:服务器地址名称
     * @param port:端口号
     * @param user:用户名
     * @param password:用户密码
     * @param path:转移到FTP服务器目录
     * @throws SocketException
     * @throws IOException
     */
    public void connectServer(String server, int port, String user, 
            String password, String path) throws SocketException, IOException { 
        ftpClient = new FTPClient(); 
        ftpClient.connect(server, port); 
        System.out.println("Connected to " + server + "."); 
        //连接成功后的回应码
        System.out.println(ftpClient.getReplyCode()); 
        ftpClient.login(user, password); 
        if (path!=null&&path.length() != 0) { 
            ftpClient.changeWorkingDirectory(path); 
        } 
     ftpClient.setBufferSize(1024);//设置上传缓存大小
     ftpClient.setControlEncoding("UTF-8");//设置编码
     ftpClient.setFileType(BINARY_FILE_TYPE);//设置文件类型
    } 
   
    /**
     * 设置传输文件类型:FTP.BINARY_FILE_TYPE | FTP.ASCII_FILE_TYPE 
     * 二进制文件或文本文件
     * @param fileType
     * @throws IOException
     */
    public void setFileType(int fileType) throws IOException { 
        ftpClient.setFileType(fileType); 
    } 
 
    /**
     * 关闭连接
     * @throws IOException
     */
    public void closeServer() throws IOException { 
        if (ftpClient!=null&&ftpClient.isConnected()) { 
         ftpClient.logout();//退出FTP服务器
            ftpClient.disconnect();//关闭FTP连接
        } 
    }
   
    /**
     * 转移到FTP服务器工作目录
     * @param path
     * @return
     * @throws IOException
     */
    public boolean changeDirectory(String path) throws IOException { 
        return ftpClient.changeWorkingDirectory(path); 
    } 
   
    /**
     * 在服务器上创建目录
     * @param pathName
     * @return
     * @throws IOException
     */
    public boolean createDirectory(String pathName) throws IOException { 
        return ftpClient.makeDirectory(pathName); 
    } 
   
    /**
     * 在服务器上删除目录
     * @param path
     * @return
     * @throws IOException
     */
    public boolean removeDirectory(String path) throws IOException { 
        return ftpClient.removeDirectory(path); 
    } 
     
    /**
     * 删除所有文件和目录
     * @param path
     * @param isAll true:删除所有文件和目录
     * @return
     * @throws IOException
     */
    public boolean removeDirectory(String path, boolean isAll) 
            throws IOException { 
         
        if (!isAll) { 
            return removeDirectory(path); 
        } 
 
        FTPFile[] ftpFileArr = ftpClient.listFiles(path); 
        if (ftpFileArr == null || ftpFileArr.length == 0) { 
            return removeDirectory(path); 
        } 
        //  
        for (FTPFile ftpFile : ftpFileArr) { 
            String name = ftpFile.getName(); 
            if (ftpFile.isDirectory()) { 
             System.out.println("* [sD]Delete subPath ["+path + "/" + name+"]");              
                removeDirectory(path + "/" + name, true); 
            } else if (ftpFile.isFile()) { 
             System.out.println("* [sF]Delete file ["+path + "/" + name+"]");                         
                deleteFile(path + "/" + name); 
            } else if (ftpFile.isSymbolicLink()) { 
 
            } else if (ftpFile.isUnknown()) { 
 
            } 
        } 
        return ftpClient.removeDirectory(path); 
    } 
   
    /**
     * 检查目录在服务器上是否存在 true:存在  false:不存在
     * @param path
     * @return
     * @throws IOException
     */
    public boolean existDirectory(String path) throws IOException { 
        boolean flag = false; 
        FTPFile[] ftpFileArr = ftpClient.listFiles(path); 
        for (FTPFile ftpFile : ftpFileArr) { 
            if (ftpFile.isDirectory() 
                    && ftpFile.getName().equalsIgnoreCase(path)) { 
                flag = true; 
                break; 
            } 
        } 
        return flag; 
    } 
 
    /**
     * 得到文件列表,listFiles返回包含目录和文件,它返回的是一个FTPFile数组
     * listNames():只包含目录的字符串数组
     * String[] fileNameArr = ftpClient.listNames(path);
     * @param path:服务器上的文件目录:/DF4
     */
    public List getFileList(String path) throws IOException { 
        FTPFile[] ftpFiles= ftpClient.listFiles(path); 
        //通过FTPFileFilter遍历只获得文件
/*      FTPFile[] ftpFiles2= ftpClient.listFiles(path,new FTPFileFilter() {
   @Override
   public boolean accept(FTPFile ftpFile) {
    return ftpFile.isFile();
   }
  });  */
        List retList = new ArrayList(); 
        if (ftpFiles == null || ftpFiles.length == 0) { 
            return retList; 
        } 
        for (FTPFile ftpFile : ftpFiles) { 
            if (ftpFile.isFile()) { 
                retList.add(ftpFile.getName()); 
            } 
        } 
        return retList; 
    } 
 
    /**
     * 删除服务器上的文件
     * @param pathName
     * @return
     * @throws IOException
     */
    public boolean deleteFile(String pathName) throws IOException { 
        return ftpClient.deleteFile(pathName); 
    } 
 
    /**
     * 上传文件到ftp服务器
     * 在进行上传和下载文件的时候,设置文件的类型最好是:
     * ftpUtil.setFileType(FtpUtil.BINARY_FILE_TYPE)
     * localFilePath:本地文件路径和名称
     * remoteFileName:服务器文件名称
     */
    public boolean uploadFile(String localFilePath, String remoteFileName) 
            throws IOException { 
        boolean flag = false; 
        InputStream iStream = null; 
        try { 
            iStream = new FileInputStream(localFilePath); 
            //我们可以使用BufferedInputStream进行封装
            //BufferedInputStream bis=new BufferedInputStream(iStream);
            //flag = ftpClient.storeFile(remoteFileName, bis);
            flag = ftpClient.storeFile(remoteFileName, iStream); 
        } catch (IOException e) { 
            flag = false; 
            return flag; 
        } finally { 
            if (iStream != null) { 
                iStream.close(); 
            } 
        } 
        return flag; 
    } 
 
    /**
     * 上传文件到ftp服务器,上传新的文件名称和原名称一样
     * @param fileName:文件名称
     * @return
     * @throws IOException
     */
    public boolean uploadFile(String fileName) throws IOException { 
        return uploadFile(fileName, fileName); 
    } 
 
    /**
     * 上传文件到ftp服务器
     * @param iStream 输入流
     * @param newName 新文件名称
     * @return
     * @throws IOException
     */
    public boolean uploadFile(InputStream iStream, String newName) 
            throws IOException { 
        boolean flag = false; 
        try { 
            flag = ftpClient.storeFile(newName, iStream); 
        } catch (IOException e) { 
            flag = false; 
            return flag; 
        } finally { 
            if (iStream != null) { 
                iStream.close(); 
            } 
        } 
        return flag; 
    } 
 
    /**
     * 从ftp服务器上下载文件到本地
     * @param remoteFileName:ftp服务器上文件名称
     * @param localFileName:本地文件名称
     * @return
     * @throws IOException
     */
    public boolean download(String remoteFileName, String localFileName) 
            throws IOException { 
        boolean flag = false; 
        File outfile = new File(localFileName); 
        OutputStream oStream = null; 
        try { 
            oStream = new FileOutputStream(outfile); 
            //我们可以使用BufferedOutputStream进行封装
          //BufferedOutputStream bos=new BufferedOutputStream(oStream);
          //flag = ftpClient.retrieveFile(remoteFileName, bos);
            flag = ftpClient.retrieveFile(remoteFileName, oStream); 
        } catch (IOException e) { 
            flag = false; 
            return flag; 
        } finally { 
            oStream.close(); 
        } 
        return flag; 
    } 
    /**
     * 从FTP中获取输入流进行文件读取
     */
    public InputStream download(String remoteFileName) 
            throws IOException { 
        InputStream is = null;
        try {
            is = ftpClient.retrieveFileStream(remoteFileName);
        } catch (IOException e) {
         e.printStackTrace();
        }
        return is; 
    }
     
    /**
     * 从ftp服务器上下载文件到本地
     * @param sourceFileName:服务器资源文件名称
     * @return InputStream 输入流
     * @throws IOException
     */
    public InputStream downFile(String sourceFileName) throws IOException { 
        return ftpClient.retrieveFileStream(sourceFileName); 
    }
}

目录
相关文章
|
3月前
|
安全 算法 网络协议
【Linux】文件服务FTP(File Transfer Protocol)
【Linux】文件服务FTP(File Transfer Protocol)
52 0
|
4月前
|
开发框架 Java 数据处理
多sheet页导出 + FTP上传文件实战
多sheet页导出 + FTP上传文件实战
|
9月前
|
网络协议 C# 文件存储
C# 利用FluentFTP实现FTP上传下载功能
C# 利用FluentFTP实现FTP上传下载功能
185 0
C# 利用FluentFTP实现FTP上传下载功能
|
1月前
|
Shell Python Windows
通过Python实现win11环境下FTP的上传与下载
通过Python实现win11环境下FTP的上传与下载
|
1月前
|
监控 安全 测试技术
使用pyftpdlib组件实现FTP文件共享
使用pyftpdlib组件实现FTP文件共享
29 0
|
2月前
|
Java
java上传、下载、预览、删除ftp服务器上的文件
java上传、下载、预览、删除ftp服务器上的文件
|
7月前
|
Apache
基于commons-net实现ftp创建文件夹、上传、下载功能.
基于commons-net实现ftp创建文件夹、上传、下载功能.
106 0
|
3月前
|
存储 数据处理
Dataphin集成任务支持自定义FTP标记完成文件内容(V3.14)
在文件传输的场景中,标记完成文件(有时也被称为标档文件)作为一种重要的确认机制被广泛应用。这一机制通过创建特定的“传输完成标识文件”,用于明确指示数据文件已成功完成全量传输,并达到可以进行下一步业务处理的状态,从而有效防止了基于不完整数据流的错误操作。
|
8月前
|
Java
Java——通过Java代码从ftp服务器下载文件
Java——通过Java代码从ftp服务器下载文件
|
4月前
|
API 分布式数据库 数据安全/隐私保护
C/C++ 实现FTP文件上传下载
FTP(文件传输协议)是一种用于在网络上传输文件的标准协议。它属于因特网标准化的协议族之一,为文件的上传、下载和文件管理提供了一种标准化的方法,在Windows系统中操作FTP上传下载可以使用WinINet库,WinINet(Windows Internet)库是 Windows 操作系统中的一个网络 API 库,用于访问 Internet 上的资源。它提供了一组函数,使开发人员能够创建网络应用程序,例如通过 HTTP 协议下载文件,发送 HTTP 请求,处理 cookie 等,本章将通过使用WinInet所提供的接口实现FTP文件上传下载功能,使得用户可以通过代码的方式上传或下载文件与FTP
75 1
C/C++ 实现FTP文件上传下载