SpringBoot整合FTP實現文件傳輸的步驟
更新時間:2023年11月02日 09:30:56 作者:松易聯@
這篇文章主要給大家介紹了SpringBoot整合FTP實現文件傳輸的步驟,文中的流程步驟和代碼示例介紹的非常詳細,對大家的學習或工作有一定的幫助,需要的朋友可以參考下
實現ftp文件傳輸的步驟:
1.ftp綁定ip端口登錄
2.切換到指定地址
3.文件下載
4.關閉ftp連接
項目中使用的jar包
<!-- ftp包-->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.9.0</version>
</dependency>
項目中使用ftp代碼:
public void getQxjFile() throws IOException {
FTPClient ftpClient = new FTPClient(); //創(chuàng)建FTP連接客戶端
ftpClient.enterLocalPassiveMode();// 設置被動模式
//ftp設置ip,端口
ftpClient.connect(costomDefineData.getQxjIp(), Integer.parseInt(costomDefineData.getQxjPort()));
//設置調用為被動模式
ftpClient.enterLocalPassiveMode();
//ftpClient.enterLocalActiveMode(); 設置為主動模式
//設置文件以二進制文件模式傳輸
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//ftp登錄
boolean loggedIn = ftpClient.login(costomDefineData.getQxjUserName(), costomDefineData.getQxjPassword());
if (loggedIn) {
System.out.println("登錄成功");
} else {
System.out.println("登錄失敗");
}
//切換到登錄后的文件夾 這里指定ftp服務器文件存放位置
boolean changed = ftpClient.changeWorkingDirectory("/");
if (changed) {
//獲取到對應的FTP文件 這是獲取對應文件夾下全部文件
FTPFile[] files = ftpClient.listFiles();
System.out.println("獲取文件個數" + files.length);
for (FTPFile file : files) {
if (file.isFile()) {
File localDir = new File(costomDefineData.getQxjFilePath() + YM + "/" + Day);
if (!localDir.exists()) {
localDir.mkdirs();
}
File localFile = new File(costomDefineData.getQxjFilePath() + YM + "/" + Day + "/" + file.getName());
if (!localFile.exists()) {
localFile.createNewFile();
}
//將ftp服務器上文件同步到本地
ftpClient.retrieveFile("/" + file.getName(), new FileOutputStream(localFile));
BufferedReader reader = new BufferedReader(new FileReader(localFile));
// 讀取文件內容并解析
String line;
String result = "";
while ((line = reader.readLine()) != null) {
// 解析每一行的數據
result = result + line;
}
}
}
//實現ftp上文件刪除
boolean deleted = ftpClient.deleteFile("/" + file.getName());
}
//ftp用戶登出
ftpClient.logout();
//ftp去掉鏈接
ftpClient.disconnect();
}
用ftp實現上傳功能
public class FTPExample {
public static void main(String[] args) {
FTPClient ftpClient = new FTPClient();
// 連接和登錄代碼省略
try {
// 上傳文件
File localFile = new File("local-file.txt");
String remoteFile = "remote-file.txt";
FileInputStream inputStream = new FileInputStream(localFile);
boolean uploaded = ftpClient.storeFile(remoteFile, inputStream);
inputStream.close();
if (uploaded) {
System.out.println("文件上傳成功!");
} else {
System.out.println("文件上傳失敗!");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 斷開連接代碼省略
}
}
}
以上就是SpringBoot整合FTP實現文件傳輸的步驟的詳細內容,更多關于SpringBoot FTP文件傳輸的資料請關注腳本之家其它相關文章!
相關文章
深入理解happens-before和as-if-serial語義
本文大部分整理自《Java并發(fā)編程的藝術》,溫故而知新,加深對基礎的理解程度。下面可以和小編來一起學習下2019-05-05

