springboot集成ftp
时间: 2023-11-08 11:05:56 浏览: 57
要在Spring Boot中集成FTP,可以使用Apache Commons Net库。首先需要在pom.xml文件中添加以下依赖项:
```
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
```
然后,可以使用以下代码连接到FTP服务器并上传文件:
```
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class FtpUploader {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String user = "username";
String password = "password";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
String remoteFile = "/path/to/remote/file.txt";
File localFile = new File("path/to/local/file.txt");
InputStream inputStream = new FileInputStream(localFile);
boolean done = ftpClient.storeFile(remoteFile, inputStream);
if (done) {
System.out.println("The file was uploaded successfully.");
}
} 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();
}
}
}
}
```