Java生成文件到ftp服务器

废话不多说,直接上代码,拿去直接可以使用。

如果小伙伴们没有可以测试ftp服务器,可以在自己的本地搭建一套ftp服务,步骤也很简单

传送门:Windows下如何搭建FTP服务并且设置其用户名和密码 (taodudu.cc)

一.引入依赖

    <dependency>
      <groupId>commons-net</groupId>
      <artifactId>commons-net</artifactId>
      <version>3.3</version>
    </dependency>

二.工具类

package com.gstanzer.supervise.utills;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author: tangbingbing
 * @date: 2023/8/11 14:16
 */
@Slf4j
public class FTPUtils {

    /**
     * 上传文件
     *
     * @param fileName    上传到FTP服务器后的文件名称
     * @param inputStream 输入文件流
     * @return
     */
    public static boolean creatFileFTP(String hostname, int port, String username, String password, String pathname, String fileName, InputStream inputStream) {

        boolean flag = false;
        FTPClient ftpClient = new FTPClient();
        //设置超时
        ftpClient.setConnectTimeout(60 * 60 * 1000);
        //设置编码
        ftpClient.setControlEncoding("UTF-8");
        try {
            //连接FTP服务器
            ftpClient.connect(hostname, port);
            //登录FTP服务器
            ftpClient.login(username, password);
            //是否成功登录FTP服务器
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                return flag;
            }
            log.info("===========登录FTP成功==============");
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //切换路径 创建路径
            ftpClient.makeDirectory(pathname);
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.enterLocalPassiveMode();

//            String pathDir1 = pathname+df.format(new Date());
//            boolean pathIsExis = ftpClient.changeWorkingDirectory(pathDir1);
//            log.info("查看文件夹是否存在");
//            if(!pathIsExis){//不存在文件夹则创建并且进入文件夹
//                ftpClient.makeDirectory(pathDir1);
//                ftpClient.changeWorkingDirectory(pathDir1);
//            }

            //设置缓冲
            ftpClient.setBufferSize(1024 * 1024 * 20);
            //保持连接
            ftpClient.setKeepAlive(true);
            boolean a = ftpClient.storeFile(new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1), inputStream);
            if (a) {
                flag = true;
                log.info("===========文件创建成功==============");
            } else {
                flag = false;
            }
            inputStream.close();
            ftpClient.logout();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 生成写入文件
     *
     * @param data 文件内容
     * @return
     */
    public static InputStream write(String data) {
        InputStream input = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
        return input;
    }

    public static void main(String[] args) {
        String data = "中文 data1\n中文 data2";
        InputStream in = write(data);
        boolean b = creatFileFTP("127.0.0.1", 21, "user", "pwd", "/", "test.txt", in);
        if (b) {
            System.out.println("文件生成并上传成功");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45443475/article/details/132226822