新闻动态

良好的口碑是企业发展的动力

java上传文件到ftp服务器

发布时间:2023-10-14 08:47:36 点击量:173
建网站服务

 

在Java中,可以使用Apache Commons Net库来实现将文件上传到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 {

private static final int BUFFER_SIZE = 4096;

 

public static void main(String[] args) {

String server = "ftp.example.com";

int port = 21;

String username = "your_username";

String password = "your_password";

String localFilePath = "path_to_local_file";

String remoteFilePath = "path_to_remote_file";

 

FTPClient ftpClient = new FTPClient();

try {

ftpClient.connect(server

port);

ftpClient.login(username

password);

ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

 

File localFile = new File(localFilePath);

FileInputStream inputStream = new FileInputStream(localFile);

 

ftpClient.storeFile(remoteFilePath

inputStream);

inputStream.close();

 

System.out.println("File uploaded successfully.");

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (ftpClient.isConnected()) {

ftpClient.logout();

ftpClient.disconnect();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

```

 

在上面的示例代码中,需要替换以下参数:

 

- `server`:FTP服务器的主机名或IP地址。

- `port`:FTP服务器的端口号,默认是21。

- `username`:登录FTP服务器的用户名。

- `password`:登录FTP服务器的密码。

- `localFilePath`:本地文件的路径。

- `remoteFilePath`:远程文件的路径。

 

请注意,上述代码仅仅上传了一个文件,如果需要上传多个文件,可在 `main` 方法中使用循环来实现。

 

希望这能帮助到你,如果还有其他问题,请随时提问。

免责声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,也不承认相关法律责任。如果您发现本社区中有涉嫌抄袭的内容,请发送邮件至:dm@cn86.cn进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。本站原创内容未经允许不得转载。
标签:
上一篇: ipconfig
下一篇: 服务器租用