使用java写一个ftp程序
时间: 2023-12-03 12:44:38 浏览: 28
好的,以下是一个简单的基于Java的FTP程序示例:
```
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
public class FTPClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("ftp.server.com", 21);
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
String user = "username";
String pass = "password";
String file = "file.txt";
sendCommand(out, "USER " + user);
sendCommand(out, "PASS " + pass);
sendCommand(out, "TYPE I");
sendCommand(out, "RETR " + file);
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fos.close();
in.close();
out.close();
socket.close();
}
private static void sendCommand(BufferedOutputStream out, String command) throws IOException {
out.write((command + "\r\n").getBytes());
out.flush();
}
}
```
此示例连接到FTP服务器,使用给定的用户名和密码进行身份验证,然后将文件下载到本地文件系统。该程序使用了传输类型“TYPE I”来指示二进制传输模式。
请注意,此示例仅适用于简单的FTP传输。实际中,您可能需要处理更多的FTP命令和错误情况。