java ftp文件服务器,java ftp文件服务器
时间: 2023-08-29 22:07:33 浏览: 166
Java提供了一些类和API来实现FTP文件服务器。以下是一个简单的FTP文件服务器的示例代码:
```java
import java.io.*;
import java.net.*;
import org.apache.commons.net.ftp.*;
public class FTPServer {
public static void main(String[] args) {
FTPServer server = new FTPServer();
server.start();
}
public void start() {
int port = 21;
try {
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("FTP Server started on port " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Accepted connection from " + clientSocket.getInetAddress().getHostAddress());
FTPConnection connection = new FTPConnection(clientSocket);
connection.start();
}
} catch (IOException ex) {
System.err.println("Error starting FTP server: " + ex.getMessage());
}
}
}
class FTPConnection extends Thread {
private Socket clientSocket;
private FTPServer server;
private FTPClient ftp;
public FTPConnection(Socket clientSocket) {
this.clientSocket = clientSocket;
this.server = server;
ftp = new FTPClient();
}
public void run() {
try {
ftp.connect(clientSocket.getInetAddress().getHostName());
ftp.login("anonymous", "");
ftp.enterLocalPassiveMode();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String line = null;
out.print("220 FTP Server ready.\r\n");
out.flush();
while ((line = in.readLine()) != null) {
if (line.startsWith("USER")) {
out.print("331 Password required for " + line.substring(5) + "\r\n");
out.flush();
} else if (line.startsWith("PASS")) {
out.print("230 User logged in.\r\n");
out.flush();
} else if (line.startsWith("QUIT")) {
out.print("221 Goodbye.\r\n");
out.flush();
break;
} else if (line.startsWith("TYPE")) {
out.print("200 Command okay.\r\n");
out.flush();
} else if (line.startsWith("LIST")) {
FTPFile[] files = ftp.listFiles();
out.print("150 Opening ASCII mode data connection for file list.\r\n");
out.flush();
for (FTPFile file : files) {
out.print(file.getName() + "\r\n");
out.flush();
}
out.print("226 Transfer complete.\r\n");
out.flush();
} else if (line.startsWith("RETR")) {
out.print("150 Opening BINARY mode data connection for " + line.substring(5) + "\r\n");
out.flush();
String fileName = line.substring(5);
OutputStream os = clientSocket.getOutputStream();
ftp.retrieveFile(fileName, os);
out.print("226 Transfer complete.\r\n");
out.flush();
} else {
out.print("502 Command not implemented.\r\n");
out.flush();
}
}
ftp.disconnect();
clientSocket.close();
} catch (IOException ex) {
System.err.println("Error handling FTP connection: " + ex.getMessage());
}
}
}
```
这个例子使用Apache Commons Net库来实现FTP连接和文件传输。它可以处理一些基本的FTP命令,如USER、PASS、LIST和RETR。你可以根据需要添加更多的功能和命令来实现一个更完整的FTP文件服务器。
阅读全文