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;
    }
}

以下是一个使用Java上传文件FTP服务器的示例代码: ```java import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class FTPUploader { public static void main(String[] args) { String server = "ftp.example.com"; int port = 21; String username = "your-username"; String password = "your-password"; File fileToUpload = new File("path/to/file.txt"); // 要上传的文件路径 FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); ftpClient.login(username, password); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); FileInputStream fileInputStream = new FileInputStream(fileToUpload); String remoteFile = "uploaded-file.txt"; // 远程服务器上保存的文件名 boolean uploaded = ftpClient.storeFile(remoteFile, fileInputStream); fileInputStream.close(); if (uploaded) { System.out.println("文件上传成功!"); } else { System.out.println("文件上传失败!"); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } } } ``` 以上代码使用了Apache Commons Net库来处理FTP相关操作。你需要将`server`、`port`、`username`和`password`替换为你的FTP服务器的相关信息,将`fileToUpload`替换为你要上传的文件路径,`remoteFile`替换为在服务器上保存的文件名。 请确保你的项目中包含了Apache Commons Net库的依赖。你可以在Maven项目中添加以下依赖: ```xml <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.8.0</version> </dependency> ``` 希望对你有所帮助!如果有任何问题,请随时问我。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值