java使用Socket实现TCP协议的excel文件从服务器下载到本机将其作为一个类写出并将下载后,基于字符流的文件写入存储作为一个类单独写出
时间: 2024-10-14 18:08:22 浏览: 31
java学习总结
在Java中,我们可以使用`java.net.Socket`类配合`java.io`包中的`InputStream`和`OutputStream`来实现实时TCP通信,并下载Excel文件。这里我会为你提供两个基本步骤的简化版代码示例:
1. **创建Server端** (用于接收请求并发送文件):
```java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
private ServerSocket serverSocket;
public void startServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
System.out.println("Server started on port " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
String fileName = in.readLine(); // 接收文件名
sendFile(clientSocket, fileName); // 发送文件
} finally {
clientSocket.close();
}
}
}
private void sendFile(Socket socket, String fileName) throws IOException {
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
socket.getOutputStream().write(buffer, 0, bytesRead);
}
fis.close();
socket.close();
}
// ...其他停止服务的操作...
}
```
2. **创建Client端** (用于发起连接并下载文件):
```java
import java.io.*;
import java.net.Socket;
public class FileClient {
public static void main(String[] args) {
try {
String serverAddress = "localhost";
int serverPort = 8000; // 修改为你服务器的实际端口
Socket socket = new Socket(serverAddress, serverPort);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String fileName = "your_excel_file.xlsx"; // 修改为你想要下载的文件名
// 请求文件
out.println(fileName);
File targetFile = new File(fileName);
FileOutputStream fos = new FileOutputStream(targetFile);
// 写入文件内容
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = socket.getInputStream().read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fos.close();
in.close();
out.close();
socket.close();
System.out.println("Download complete.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这两个类分别实现了服务器端接收请求、发送文件和客户端请求文件、保存文件的功能。注意实际部署时,你需要处理异常并添加适当的错误处理。
阅读全文