Nio 中的方法 - 文件上传

原文 MINA

nio 基本用法

 

​​​​​​​java.nio.file.Files;

​​​​​​​

​​​​​​​createDirectory - 创建目录

示例

public void init() {
        try {
            Path rootLocation = Paths.get("/tmp");
            Files.createDirectory(rootLocation);
        } catch (IOException e) {
            throw new StorageException("Could not initialize storage", e);
        }
    }

 

copy - 复制文件到指定路径

示例

public void store(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                throw new StorageException("Failed to store empty file " + file.getOriginalFilename());
            }

            Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));

        } catch (IOException e) {
            throw new StorageException("Failed to store file " + file.getOriginalFilename(), e);
        }
    }

其中,Path 的 resolve方法:根据文件名中解析得到完整Path。

 

walk - 遍历指定路径下的文件到流中(可以通过 json返回给页面)

public static java.util.stream.Stream<java.nio.file.Path> walk(java.nio.file.Path start,
                                                               int maxDepth,
                                                               @NotNull java.nio.file.FileVisitOption... options)
                                                       throws java.io.IOException

示例

public Stream<Path> loadAll() {
        try {

            return Files.walk(this.rootLocation, 1)
                    .filter(path -> !path.equals(this.rootLocation))
                    .map(this.rootLocation::relativize);

        } catch (IOException e) {
            throw new StorageException("Failed to read stored files", e);
        }

    }

其中,Stream的 filter 和 map方法:对Stream进行一些修正。

 

FileSystemUtils - springframework 的工具类,递归删除

public void deleteAll() {
    FileSystemUtils.deleteRecursively(rootLocation.toFile());
}

--

项目地址 http://git.oschina.net/lemosd/gs-uploading-files

转载于:https://my.oschina.net/lemos/blog/885461

好的,下面是一个简单的基于 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"); } } } ``` 这里只是一个简单的示例代码,实际应用还需要考虑一些异常和错误处理等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值