java 通过socket传来的MappedByteBuffer 用RandomAccessFile随机写入文件块 最后拼接成完整文件 完整代码
时间: 2024-04-11 22:26:13 浏览: 99
以下是一个示例代码,展示了如何使用 `MappedByteBuffer` 和 `RandomAccessFile` 来接收通过 Socket 传来的文件块,并将其按顺序写入磁盘,最终拼接成完整文件。
```java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class FileReceiver {
private static final int PORT = 9999;
private static final String SAVE_PATH = "/path/to/save/file.txt";
private static final int BUFFER_SIZE = 4096; // 缓冲区大小
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("等待连接...");
Socket socket = serverSocket.accept();
System.out.println("连接成功.");
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
RandomAccessFile randomAccessFile = new RandomAccessFile(SAVE_PATH, "rw");
FileChannel fileChannel = randomAccessFile.getChannel();
long fileSize = dataInputStream.readLong();
long receivedSize = 0;
while (receivedSize < fileSize) {
long remaining = fileSize - receivedSize;
int bufferSize = (int) Math.min(remaining, BUFFER_SIZE);
MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, receivedSize, bufferSize);
int bytesRead = dataInputStream.read(buffer.array(), 0, bufferSize);
buffer.limit(bytesRead);
buffer.force();
receivedSize += bytesRead;
}
fileChannel.close();
randomAccessFile.close();
dataInputStream.close();
socket.close();
serverSocket.close();
System.out.println("文件接收完成.");
}
}
```
这个示例代码创建了一个服务器端,监听指定端口。当客户端连接成功后,服务器端接收文件的大小信息,并通过 `MappedByteBuffer` 和 `RandomAccessFile` 来接收和写入文件块。最后,关闭相关资源并打印完成信息。
请注意,这只是一个简单的示例,实际使用中可能需要添加错误处理、进度显示和其他的功能。
阅读全文