java 写一个ftp
时间: 2024-03-11 12:47:49 浏览: 68
java编写FTP
4星 · 用户满意度95%
要实现一个FTP,需要使用Java中的FTP客户端库。常用的FTP客户端库有Apache Commons Net和Java FTP Client。
下面是使用Apache Commons Net实现FTP上传文件的示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class FtpClientExample {
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);
File localFile = new File("localfile.txt");
String remoteFile = "remotefile.txt";
FileInputStream inputStream = new FileInputStream(localFile);
System.out.println("Start uploading file");
boolean done = ftpClient.storeFile(remoteFile, inputStream);
inputStream.close();
if (done) {
System.out.println("The file is uploaded successfully.");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
```
这段代码通过FTP连接到服务器,设置传输模式为二进制模式,然后上传一个本地文件到FTP服务器。可以根据需要修改代码实现其他FTP操作。
阅读全文