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