FTP上传下载工具类

import java.io.ByteArrayOutputStream;
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 org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @khj
 * @title FtpUtils
 * @Description : FTP 上传下载工具类
 * @time
 */
public class FTPUtils
{
    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger(FTPUtils.class);
    
    private static FTPClient ftp;
    
    /**
     * 连接ftp <一句话功能简述> <功能详细描述>
     * 
     * @param addr
     * @param port
     * @param username
     * @param password
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static boolean connect(String addr, int port, String username, String password)
    {
        ftp = new FTPClient();
        
        try
        {
            ftp.connect(addr, 21);
            ftp.login(username, password);
            
        }
        catch (SocketException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return ftp.isConnected();
    }
    
    @SuppressWarnings("unused")
    private void upload(File file, String path)
    {
        logger.info(" file.isDirectory() : {}" + file.isDirectory());
        
        try
        {
            if (file.isDirectory())
            {
                ftp.makeDirectory(file.getName());
                ftp.changeWorkingDirectory(file.getName());
                String[] files = file.list();
                for (int i = 0; i < files.length; i++)
                {
                    File file1 = new File(file.getPath() + "\\" + files[i]);
                    if (file1.isDirectory())
                    {
                        upload(file1, path);
                        ftp.changeToParentDirectory();
                    }
                    else
                    {
                        File file2 = new File(file.getPath() + "\\" + files[i]);
                        FileInputStream input = new FileInputStream(file2);
                        ftp.storeFile(file2.getName(), input);
                        input.close();
                    }
                }
            }
            else
            {
                File file2 = new File(file.getPath());
                
                System.out.println(" file.getPath() : " + file.getPath() + " | file2.getName() : " + file2.getName());
                
                InputStream input = new FileInputStream(file2);
                
                ftp.changeWorkingDirectory(path);
                ftp.storeFile(file2.getName(), input);
                
                input.close(); // 关闭输入流
                ftp.logout(); // 退出连接
            }
        }
        catch (Exception e)
        {
            logger.error(e.getMessage());
        }
    }
    
    @SuppressWarnings("static-access")
    public static byte[] downloadFile(String fileName)
    {
        byte[] bytes = null;
        try
        {
            ftp.changeWorkingDirectory("");
            
            // 列出该目录下所有文件
            FTPFile[] fs = ftp.listFiles(fileName);
            
            // 遍历所有文件,找到指定的文件
            for (FTPFile file : fs)
            {
                if (file.getName().equals(fileName))
                {
                    // 根据绝对路径初始化文件
                    // File localFile = new File(localPath);
                    // if (!localFile.exists())
                    // {
                    // localFile.createNewFile();
                    // }
                    // // 输出流
                    // OutputStream os = new FileOutputStream(localFile);
                    InputStream in = null;
                    // 下载文件
                    ftp.setBufferSize(1024);
                    ftp.setControlEncoding("UTF-8");
                    ftp.setFileType(ftp.BINARY_FILE_TYPE);
                    // 下载文件到 localFile
                    // ftp.retrieveFile(ff.getName(), os);
                    
                    String remoteAbsoluteFile = file.getName();
                    remoteAbsoluteFile = new String(remoteAbsoluteFile.getBytes("UTF-8"), "ISO-8859-1");
                    in = ftp.retrieveFileStream(remoteAbsoluteFile);
                    
                    bytes = input2byte(in);
                
                    System.out.println("下载成功!" + bytes.length);
                    
                    in.close();
                }
            }
            
            ftp.logout(); // 退出连接
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return bytes;
    }
    
    /**
     * byte[] 转 file 
     * 
     * @param bytes
     * @param path
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static void byteToFile(byte[] bytes, String path)
    {
        try
        {
            // 根据绝对路径初始化文件
            File localFile = new File(path);
            if (!localFile.exists())
            {
                localFile.createNewFile();
            }
            // 输出流
            OutputStream os = new FileOutputStream(localFile);
            
            os.write(bytes);
            
            os.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    /**
     * 文件转成 byte[] <一句话功能简述> <功能详细描述>
     * 
     * @param inStream
     * @return
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    public static byte[] input2byte(InputStream inStream)
        throws IOException
    {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0)
        {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        
        swapStream.close();
        
        return in2b;
    }
    
    public static void getPhoto(String filePath,String localPath)
    {
        FTPUtils.connect(ReadPropertiesUtils.getParamValue("ftp.host"),
            21,
            ReadPropertiesUtils.getParamValue("ftp.username"),
            ReadPropertiesUtils.getParamValue("ftp.password"));
        logger.info("");
        byte[] bytes = FTPUtils.downloadFile(filePath);
        
        FTPUtils.byteToFile(bytes, localPath);
    }
    
    public static byte[] getPhoto(String filePath)
    {
        FTPUtils.connect(ReadPropertiesUtils.getParamValue("ftp.host"),
            21,
            ReadPropertiesUtils.getParamValue("ftp.username"),
            ReadPropertiesUtils.getParamValue("ftp.password"));
        logger.info("");
        byte[] bytes = FTPUtils.downloadFile(filePath);
        
        //FTPUtils.byteToFile(bytes, localPath);
        return bytes;
    }
    
    public static void main(String[] args)
        throws Exception
    {
        
        String filePath = "T_ZDRY_IDX_JXXX_INC/010020090902731604.jpg";
        
        String localPath = "d:\\ccc.jpg";
        
        FTPUtils.getPhoto(filePath, localPath);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
sun.net.ftp.ftpclient 工具类是 Java 中内置的 FTP 客户端工具类,可以用于实现 FTP 文件上下载等操作。下面是一个使用 sun.net.ftp.ftpclient 工具类实现文件上的示例代码: ```java import sun.net.ftp.FtpClient; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class FTPUploader { public static void main(String[] args) { String server = "ftp.example.com"; // FTP 服务器地址 int port = 21; // FTP 服务器端口号 String user = "username"; // FTP 登录用户名 String password = "password"; // FTP 登录密码 String remoteDir = "/upload/"; // 远程目录,注意要以 / 结尾 String localFile = "local_file.txt"; // 本地文件名 try (FtpClient ftpClient = FtpClient.create(server)) { ftpClient.login(user, password.toCharArray()); // 登录 FTP 服务器 ftpClient.changeDirectory(remoteDir); // 切换到远程目录 File file = new File(localFile); try (InputStream inputStream = new FileInputStream(file)) { ftpClient.putFile(file.getName(), inputStream); // 上文件 System.out.println("File uploaded successfully."); } } catch (IOException e) { e.printStackTrace(); } } } ``` 在示例代码中,我们通过 `FtpClient.create(server)` 创建了一个 FTP 客户端对象,然后使用 `ftpClient.login(user, password.toCharArray())` 方法登录 FTP 服务器,接着使用 `ftpClient.changeDirectory(remoteDir)` 方法切换到远程目录,最后使用 `ftpClient.putFile(file.getName(), inputStream)` 方法上文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值