使用java写一个ftp程序
时间: 2023-12-03 09:44:49 浏览: 109
一个用Java写的FTP服务器程序
4星 · 用户满意度95%
好的,以下是一个简单的 Java FTP 程序:
```java
import java.io.*;
import java.net.*;
public class FTPClient {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String user = "username";
String pass = "password";
String remoteFilePath = "/path/to/remote/file.txt";
String localFilePath = "/path/to/local/file.txt";
try {
// 连接 FTP 服务器
Socket socket = new Socket(server, port);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// 读取 FTP 服务器的欢迎信息
String response = reader.readLine();
System.out.println("FTP Server says: " + response);
// 发送用户名和密码
writer.write("USER " + user + "\r\n");
writer.flush();
response = reader.readLine();
System.out.println("FTP Server says: " + response);
writer.write("PASS " + pass + "\r\n");
writer.flush();
response = reader.readLine();
System.out.println("FTP Server says: " + response);
// 切换到被动模式
writer.write("PASV\r\n");
writer.flush();
response = reader.readLine();
System.out.println("FTP Server says: " + response);
// 解析被动模式的响应信息,获取数据传输端口号
String[] parts = response.split(",");
int port1 = Integer.parseInt(parts[4]);
int port2 = Integer.parseInt(parts[5].substring(0, parts[5].length() - 2));
int dataPort = (port1 << 8) + port2;
// 建立数据传输连接
Socket dataSocket = new Socket(server, dataPort);
DataOutputStream dataOutput = new DataOutputStream(dataSocket.getOutputStream());
// 下载文件
writer.write("RETR " + remoteFilePath + "\r\n");
writer.flush();
response = reader.readLine();
System.out.println("FTP Server says: " + response);
BufferedInputStream input = new BufferedInputStream(dataSocket.getInputStream());
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(localFilePath));
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
output.close();
input.close();
dataOutput.close();
dataSocket.close();
socket.close();
System.out.println("File downloaded successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
上面的程序演示了如何连接 FTP 服务器、下载文件并保存到本地。你可以根据自己的需求进行修改和扩展。注意,这里只是一个简单的示例程序,实际使用中可能需要更多的错误处理和安全措施。
阅读全文