NIO实现文件下载

public static void downloadFile(File file, HttpServletResponse response){
        OutputStream os = null;
        try {
            // 取得输出流
            os = response.getOutputStream();
            String contentType = Files.probeContentType(Paths.get(file.getAbsolutePath()));
            response.setHeader("Content-Type", contentType);
            response.setHeader("Content-Disposition", "attachment;filename="+ new String(file.getName().getBytes("utf-8"),"ISO8859-1"));
            FileInputStream fileInputStream = new FileInputStream(file);
            WritableByteChannel writableByteChannel = Channels.newChannel(os);
            FileChannel fileChannel = fileInputStream.getChannel();
            fileChannel.transferTo(0,fileChannel.size(),writableByteChannel);
            fileChannel.close();
            os.flush();
            writableByteChannel.close();
        } catch (IOException e) {
           e.printStackTrace();
        }
        //文件的关闭放在finally中
        finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

原文链接:https://blog.csdn.net/qiuxinfa123/article/details/109099000

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 NIO 实现多客户端下载文件,需要采取以下步骤: 1. 创建一个 ServerSocketChannel,绑定监听端口 2. 创建 Selector 对象 3. 将 ServerSocketChannel 注册到 Selector 上,监听 OP_ACCEPT 事件 4. 在 OP_ACCEPT 事件发生时,accept 客户端连接,并将 SocketChannel 注册到 Selector 上,监听 OP_READ 事件 5. 在 OP_READ 事件发生时,读取客户端发送的数据,解析出需要下载的文件路径和文件名 6. 打开要下载的文件,准备传输数据 7. 将文件数据写入到 SocketChannel 中,使用 FileChannel.transferTo() 方法实现 8. 在传输完成后关闭 SocketChannel 和 ServerSocketChannel 以下是示例代码: ```java public class NioFileServer { public static void main(String[] args) throws IOException { int port = 8888; ServerSocketChannel server = ServerSocketChannel.open(); server.socket().bind(new InetSocketAddress(port)); server.configureBlocking(false); Selector selector = Selector.open(); server.register(selector, SelectionKey.OP_ACCEPT); while (true) { selector.select(); Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectionKeys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); if (key.isAcceptable()) { SocketChannel client = server.accept(); client.configureBlocking(false); client.register(selector, SelectionKey.OP_READ); } else if (key.isReadable()) { SocketChannel client = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(1024); client.read(buffer); String request = new String(buffer.array()).trim(); String[] parts = request.split(" "); String filePath = parts[1]; File file = new File(filePath); if (file.exists()) { FileChannel fileChannel = new FileInputStream(file).getChannel(); client.write(fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length())); fileChannel.close(); } else { client.write(ByteBuffer.wrap("File not found".getBytes())); } client.close(); } iterator.remove(); } } } } ``` 在客户端,可以使用 Socket 来连接服务器,并向服务器发送请求: ```java public class NioFileClient { public static void main(String[] args) throws IOException { String host = "localhost"; int port = 8888; Socket socket = new Socket(host, port); OutputStream outputStream = socket.getOutputStream(); String request = "GET /path/to/file HTTP/1.1\r\n\r\n"; outputStream.write(request.getBytes()); InputStream inputStream = socket.getInputStream(); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1) { System.out.println(new String(buffer, 0, len)); } socket.close(); } } ``` 注意:以上示例代码仅供参考,请根据具体需求进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值