Fork me on GitHub

java上传文件到FTP制定文件夹

JAVA 上传文件到FTP

/**
 * @ClassName FTPLoad
 * @Description TODO
 * @Author dell
 * @Date 2024/3/14 15:56
 * @Version 1.0
 **/
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class FTPUpload {

    public static void main(String[] args) {
        String projectRoot = System.getProperty("user.dir");
        String filePath = Paths.get(projectRoot, "config/application3ke.json").toString();


        JSONObject obj=JSONUtil.parseObj(readJson(filePath));
        String server = obj.getStr("server");
        int port = obj.getInt("port");
        String user = obj.getStr("username");
        String password = obj.getStr("password");
        String localBase = obj.getStr("localBase");//本地预处理文件夹路径
        String saveBackupFile = obj.getStr("saveBackupFile");//预处理文件处理结束后的备份保存路径
        String remoteDirectoryPath = obj.getStr("remoteDirectoryPath");//远程FTP文件夹路径

        File dir1 = new File(localBase);
        File[] dirs = dir1.listFiles();


        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(server, port);
            ftpClient.login(user, password);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.setBufferSize(1024000);
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
                    "OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
                ftpClient.setControlEncoding("UTF-8");
            }else {
                ftpClient.setControlEncoding("GBK");
            }
            if (dirs!=null){
                //
                for (File dir : dirs) {//变量文件夹
                    System.out.println(dir.getName());
                    if (dir.isDirectory()) {
                        File dir2 = new File(dir.getPath());//取到二级目录
                        File[] files = dir2.listFiles();
                        String remoteDirectoryPathchange=remoteDirectoryPath+dir.getName();
                        ftpClient.changeWorkingDirectory(new String(remoteDirectoryPathchange.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));

                        for (File file : files){

                            File localFile = new File(file.getPath());
                            FileInputStream inputStream = new FileInputStream(localFile);

                            String remoteFilePath =  localFile.getName();
                            boolean uploaded = ftpClient.storeFile(new String(remoteFilePath.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1), inputStream);
                            inputStream.close();

                            if (uploaded) {
                                String targetFolderPath=saveBackupFile+dir.getName();
                                //将该文件移动到saveBackFile文件夹下面
                                moveFile(file.getPath(),targetFolderPath);
                                System.out.println("File uploaded successfully to: " + remoteFilePath);
                            } else {
                                System.out.println("Failed to upload file.");
                            }

                        }

                    }
                }
            }


        } catch (IOException ex) {
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    public static void moveFile(String sourceFilePath, String targetFolderPath) {
        // 创建源文件路径对象和目标文件夹路径对象
        Path sourcePath = Paths.get(sourceFilePath);
        Path targetPath = Paths.get(targetFolderPath);

        // 检查目标文件夹是否存在,如果不存在则创建
        if (!Files.exists(targetPath)) {
            try {
                Files.createDirectories(targetPath);
                System.out.println(targetPath+"目标文件夹不存在,已创建。");
            } catch (IOException e) {
                System.err.println("无法创建目标文件夹: " + e.getMessage());
                return;
            }
        }

        try {
            // 移动文件到目标文件夹-覆盖式
            Files.move(sourcePath, targetPath.resolve(sourcePath.getFileName()), StandardCopyOption.REPLACE_EXISTING);

            System.out.println("文件移动成功!");
        } catch (IOException e) {
            System.err.println("文件移动失败: " + e.getMessage());
        }
    }

    public static JSONObject readJson(String jsonFilePath){
        // 指定 JSON 文件路径
        JSONObject jsonObject=new JSONObject();
        try {
            // 读取 JSON 文件内容为字符串
            String jsonString = FileUtil.readString(jsonFilePath, Charset.defaultCharset());

            // 使用 Hutool 的 JSONUtil 解析 JSON 字符串
            jsonObject = JSONUtil.parseObj(jsonString);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
}

posted @ 2024-03-15 17:17  壶小旭  阅读(151)  评论(0编辑  收藏  举报