java 通过socket传来的buffer 用RandomAccessFile随机写入文件块 最后拼接成完整文件 完整代码
时间: 2024-04-11 19:26:06 浏览: 79
以下是一个完整的Java代码示例,演示了通过Socket传来的buffer使用RandomAccessFile随机写入文件块,并最后拼接成完整文件的过程:
```java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
public static void main(String[] args) {
int port = 8888;
String outputFile = "output.txt";
int bufferSize = 1024;
try {
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server started. Listening on port " + port);
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());
RandomAccessFile file = new RandomAccessFile(outputFile, "rw");
byte[] buffer = new byte[bufferSize];
int bytesRead;
while ((bytesRead = clientSocket.getInputStream().read(buffer)) != -1) {
file.write(buffer, 0, bytesRead);
}
file.close();
clientSocket.close();
serverSocket.close();
System.out.println("File received and saved as " + outputFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请注意,上述代码仅为演示用途,实际使用时还应该进行错误处理、边界条件检查等。另外,还需要根据实际需求进行适当的修改,比如更改监听的端口、指定输出文件的路径等。
阅读全文