Java使用NIO优化IO实现文件上传下载功能

yizhihongxing

我来为您讲解一下“Java使用NIO优化IO实现文件上传下载功能”的完整攻略。

概述

Java NIO library 是Java语言提供的一种基于缓冲区、非阻塞的IO,使得Java应用程序能够快速轻便地处理并发客户端请求。使用Java NIO实现文件上传下载功能的好处是可以大大提高系统的吞吐量、降低系统的IO延迟,而且还能避免阻塞线程,提高服务器的并发能力。

Java NIO

Java NIO的核心概念包括通道(Channel)、缓冲区(Buffer)、选择器(Selector)和文件锁(FileLock)。其中,通道负责连接数据源,缓冲区负责存储数据,选择器负责监听通道的事件,文件锁提供了文件级别的共享锁。

文件上传实现

  1. 创建文件上传的服务器端代码
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class NioServer {

    public static void main(String[] args) throws Exception {

        java.net.ServerSocket serverSocket = new java.net.ServerSocket(8888);

        System.out.println("NioServer has started");

        while (true) {

            SocketChannel socketChannel = SocketChannel.open();
            java.net.Socket socket = serverSocket.accept();
            System.out.println(socket.getInetAddress() + " is connected");

            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (socketChannel.read(buffer) != -1) {
                buffer.flip();
                Charset charset = Charset.forName("UTF-8");
                String message = new String(buffer.array(), 0, buffer.limit(), charset);
                System.out.println(message);
                buffer.clear();
            }

            String fileName = "C:\\tmp\\fileupload\\temp.log";
            FileChannel outChannel = new FileOutputStream(fileName).getChannel();
            ByteBuffer buffer1 = ByteBuffer.allocate(1024);

            long fileSize = socketChannel.read(buffer1);
            while (fileSize > 0) {
                buffer1.flip();
                outChannel.write(buffer1);
                buffer1.clear();
                fileSize = socketChannel.read(buffer1);
            }

            File file = new File(fileName);
            System.out.println(file.getName() + "has been saved at: " + file.getAbsolutePath());
            outChannel.close();
            socketChannel.close();
        }
    }
}
  1. 创建文件上传的客户端代码
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class NioClient {

    public static void main(String[] args) throws Exception {

        String filePath = "C:\\tmp\\fileupload\\test.log";
        File file = new File(filePath);
        String fileName = file.getName();

        SocketChannel socketChannel = SocketChannel.open(new java.net.InetSocketAddress("localhost", 8888));

        Charset charset = Charset.forName("UTF-8");
        ByteBuffer buffer1 = ByteBuffer.allocate(1024);
        buffer1.put(fileName.getBytes(charset));
        buffer1.flip();
        socketChannel.write(buffer1);

        FileChannel inChannel = new FileInputStream(file).getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (inChannel.read(buffer) != -1) {
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }

        inChannel.close();
        socketChannel.close();
    }
}

文件下载实现

  1. 创建文件下载的服务器端代码
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class NioServer {

    public static void main(String[] args) throws Exception {

        java.net.ServerSocket serverSocket = new java.net.ServerSocket(8888);

        System.out.println("NioServer has started");

        while (true) {

            SocketChannel socketChannel = SocketChannel.open();
            java.net.Socket socket = serverSocket.accept();
            System.out.println(socket.getInetAddress() + " is connected");

            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (socketChannel.read(buffer) != -1) {
                buffer.flip();
                Charset charset = Charset.forName("UTF-8");
                String message = new String(buffer.array(), 0, buffer.limit(), charset);
                System.out.println(message);
                buffer.clear();
            }

            String filePath = "C:\\tmp\\filedownload\\" + message.trim();
            File file = new File(filePath);
            if (!file.exists()) {
                System.out.println("File does not exist");
            } else {
                FileChannel inChannel = new FileInputStream(file).getChannel();
                ByteBuffer buffer1 = ByteBuffer.allocate(1024);
                int bytesRead;
                while ((bytesRead = inChannel.read(buffer1)) != -1) {
                    buffer1.flip();
                    socketChannel.write(buffer1);
                    buffer1.clear();
                }

                System.out.println(file.getName() + "has been downloaded from: " + file.getAbsolutePath());
                inChannel.close();
            }

            socketChannel.close();
        }
    }
}
  1. 创建文件下载的客户端代码
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class NioClient {

    public static void main(String[] args) throws Exception {

        String fileName = "test.log";
        SocketChannel socketChannel = SocketChannel.open(new java.net.InetSocketAddress("localhost", 8888));

        Charset charset = Charset.forName("UTF-8");
        ByteBuffer buffer1 = ByteBuffer.allocate(1024);
        buffer1.put(fileName.getBytes(charset));
        buffer1.flip();
        socketChannel.write(buffer1);

        String filePath = "C:\\tmp\\filedownload\\temp.log";
        FileChannel outChannel = new FileOutputStream(filePath).getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        long fileSize = socketChannel.read(buffer);
        while (fileSize > 0) {
            buffer.flip();
            outChannel.write(buffer);
            buffer.clear();
            fileSize = socketChannel.read(buffer);
        }

        File file = new File(filePath);
        System.out.println(file.getName() + "has been saved at: " + file.getAbsolutePath());
        outChannel.close();
        socketChannel.close();
    }
}

以上就是Java使用NIO优化IO实现文件上传下载功能的完整攻略,希望对您有所帮助。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java使用NIO优化IO实现文件上传下载功能 - Python技术站

(0)
上一篇 2023年5月19日
下一篇 2023年5月19日

相关文章

  • Spring MVC自定义日期类型转换器实例详解

    Spring MVC自定义日期类型转换器实例详解 1. 什么是日期类型转换器? Spring MVC在处理表单数据时,会将用户提交的数据绑定到Controller的方法参数或者是JavaBean里面,但是很多数据是无法直接转换为Java的内置类型,比如日期类型。这个时候就需要使用日期类型转换器来进行转换。日期类型转换器的作用是将用户提交的日期字符串或者其他格…

    Java 2023年6月15日
    00
  • java读取其他服务接口返回的json数据示例代码

    下面是完整攻略: 准备工作 首先,我们需要导入 org.json.JSONObject 包,这个包可以帮助我们轻松地处理 JSON 数据。 接下来,创建 HTTPURLConnection 类型的对象,比如命名为 connection。然后用 connection.connect() 连接到服务端接口。 读取服务接口返回的数据 读取服务端接口返回的数据需要使…

    Java 2023年5月26日
    00
  • java之使用stream对日期排序方式

    下面是对Java中使用Stream对日期排序的攻略。 1. 准备数据 在讲解如何使用Stream对日期排序之前,我们需要准备一些数据。假设我们有一个List集合,其中包含多个日期对象。如下所示: List<LocalDate> dates = Arrays.asList( LocalDate.of(2021, 8, 1), LocalDate.o…

    Java 2023年5月20日
    00
  • struts2 validation.xml 验证规则代码解析

    为了让大家更好地理解和使用Struts2的数据验证功能,我们先来详细讲解一下“struts2 validation.xml 验证规则代码解析”的完整攻略。 一、Struts2数据验证简介 Struts2是一款基于MVC架构模式的web应用程序开发框架,可以快速地搭建一个web应用程序。在web应用程序的业务逻辑中,有时需要对用户提交的请求参数进行验证,比如用…

    Java 2023年5月20日
    00
  • JavaScript代码调试方法实例小结

    我来为您详细讲解“JavaScript代码调试方法实例小结”的完整攻略。 1. 什么是JavaScript代码调试? JavaScript代码调试是指在开发过程中,通过各种工具或方法找出程序代码中的错误或问题,并进行修复的过程。JavaScript是一种高级动态语言,一些问题可能会出现在运行时,因此调试是非常重要的。 2. JavaScript代码调试的方法…

    Java 2023年5月26日
    00
  • Java8中使用一行代码读取文件

    想要在Java8中使用一行代码读取文件,可以使用Files类中的readString()方法。方法接收一个文件路径参数并返回一个字符串,其中包含整个文件的内容。下面是一个完整的攻略: 步骤一:导入必要的Java库 Java8中读取文件需要用到java.nio.file.Files类,因此需要在类的开头导入此类: import java.nio.file.Fi…

    Java 2023年5月20日
    00
  • 浅析NIO系列之TCP

    浅析NIO系列之TCP攻略 什么是NIO NIO(New IO)是Java自从1.4版本后提供的新IO API,可以更快的进行IO操作和更多的IO操作,这与以前的IO API相比较是一个很大的改进。 NIO最核心的是Channel、Buffer和Selector。 什么是TCP TCP(Transmission Control Protocol)即传输控制协…

    Java 2023年5月20日
    00
  • ASP.NET+Web服务实现软件共享

    ASP.NET是一种基于微软的.NET框架的Web开发技术,可以用来开发Web应用程序和Web服务。Web服务是一种通过网络调用的应用程序,可以与不同的平台和语言进行交互。因此,使用ASP.NET和Web服务可以实现软件的共享,方便多个平台和语言之间的数据传输和交互。 以下是实现软件共享的ASP.NET+Web服务攻略: 创建Web服务 首先需要创建一个AS…

    Java 2023年6月15日
    00
合作推广
合作推广
分享本页
返回顶部