java socket传输文件 用RandomAccessFile和MappedByteBuffer读写
时间: 2024-04-10 21:27:04 浏览: 124
你可以使用RandomAccessFile和MappedByteBuffer来实现Java Socket文件传输。以下是一个简单的示例代码:
```java
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
public class FileTransferServer {
public static void main(String[] args) {
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(8080));
System.out.println("等待客户端连接...");
SocketChannel socketChannel = serverSocketChannel.accept();
System.out.println("客户端已连接。");
File file = new File("example.txt");
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel fileChannel = randomAccessFile.getChannel();
long fileSize = file.length();
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, fileSize);
socketChannel.write(ByteBuffer.wrap(Long.toString(fileSize).getBytes()));
System.out.println("开始传输文件...");
socketChannel.write(mappedByteBuffer);
System.out.println("文件传输完成。");
socketChannel.close();
serverSocketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
```java
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
public class FileTransferClient {
public static void main(String[] args) {
try {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("localhost", 8080));
ByteBuffer fileSizeBuffer = ByteBuffer.allocate(8);
socketChannel.read(fileSizeBuffer);
fileSizeBuffer.flip();
long fileSize = Long.parseLong(new String(fileSizeBuffer.array()).trim());
System.out.println("开始接收文件...");
RandomAccessFile randomAccessFile = new RandomAccessFile("received.txt", "rw");
FileChannel fileChannel = randomAccessFile.getChannel();
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, fileSize);
socketChannel.read(mappedByteBuffer);
System.out.println("文件接收完成。");
socketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
其中,Server端将文件example.txt传输给Client端,并保存为received.txt。你可以根据需要修改文件名和路径。请确保Server端先运行,然后再运行Client端。这只是一个简单的示例,你可以根据自己的需求进行修改和扩展。
阅读全文
相关推荐



















