用 nio 写一个文件上传
时间: 2023-09-14 20:05:55 浏览: 93
使用io实现文件上传
好的,下面是一个简单的基于 NIO 的文件上传示例代码:
```java
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FileUploader {
private static final int BUFFER_SIZE = 1024;
public static void main(String[] args) throws IOException {
// 服务端监听的端口号
int port = 8888;
// 要接收的文件保存的目录
Path saveDir = Paths.get("/path/to/save/dir");
// 创建服务端 SocketChannel
try (ServerSocketChannel serverChannel = ServerSocketChannel.open()) {
serverChannel.socket().bind(new InetSocketAddress(port));
System.out.println("Server started on port " + port);
// 循环等待客户端连接
while (true) {
SocketChannel clientChannel = serverChannel.accept();
System.out.println("Client connected: " + clientChannel.getRemoteAddress());
// 解析客户端发送的文件名和文件大小
ByteBuffer buffer = ByteBuffer.allocate(2 * Integer.BYTES);
clientChannel.read(buffer);
buffer.flip();
int fileNameLength = buffer.getInt();
int fileSize = buffer.getInt();
// 接收文件数据并保存到本地文件
Path savePath = saveDir.resolve(new String(buffer.array(), Integer.BYTES, fileNameLength));
try (FileChannel fileChannel = FileChannel.open(savePath, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) {
buffer = ByteBuffer.allocate(BUFFER_SIZE);
int bytesRead;
while ((bytesRead = clientChannel.read(buffer)) != -1) {
buffer.flip();
fileChannel.write(buffer);
buffer.compact();
if (fileChannel.position() == fileSize) {
break;
}
}
buffer.flip();
while (buffer.hasRemaining()) {
fileChannel.write(buffer);
}
}
System.out.println("File saved as " + savePath);
clientChannel.close();
}
}
}
}
```
客户端上传文件的代码如下:
```java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FileUploader {
private static final int BUFFER_SIZE = 1024;
public static void main(String[] args) throws IOException {
// 服务端的 IP 和监听的端口号
String host = "localhost";
int port = 8888;
// 要上传的文件路径
Path filePath = Paths.get("/path/to/upload/file");
// 创建客户端 SocketChannel
try (SocketChannel clientChannel = SocketChannel.open()) {
clientChannel.connect(new InetSocketAddress(host, port));
System.out.println("Connected to server: " + clientChannel.getRemoteAddress());
// 发送文件名和文件大小
String fileName = filePath.getFileName().toString();
ByteBuffer buffer = ByteBuffer.allocate(2 * Integer.BYTES + fileName.length());
buffer.putInt(fileName.length());
buffer.putInt((int) Files.size(filePath));
buffer.put(fileName.getBytes());
buffer.flip();
clientChannel.write(buffer);
// 发送文件数据
try (FileChannel fileChannel = FileChannel.open(filePath, StandardOpenOption.READ)) {
buffer = ByteBuffer.allocate(BUFFER_SIZE);
int bytesRead;
while ((bytesRead = fileChannel.read(buffer)) != -1) {
buffer.flip();
clientChannel.write(buffer);
buffer.compact();
}
buffer.flip();
while (buffer.hasRemaining()) {
clientChannel.write(buffer);
}
}
System.out.println("File uploaded successfully");
}
}
}
```
这里只是一个简单的示例代码,实际应用中还需要考虑一些异常和错误处理等问题。
阅读全文