国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
1 NIO的一些基礎預備知識
2 NIO為何較傳統(tǒng)的io速度較快
3 NIO實戰(zhàn)上傳下載
3.1 url下載文件
3.2 通過NIO上傳文件
Home Java javaTutorial How does Java use NIO to optimize IO to implement file upload and download functions?

How does Java use NIO to optimize IO to implement file upload and download functions?

May 12, 2023 pm 09:31 PM
java io nio

1 NIO的一些基礎預備知識

Java中IO流類的體系中BIO與NIO:https://blog.csdn.net/ZGL_cyy/article/details/104326458
Java IO體系與NIO和BIO體系面試題 :https://blog.csdn.net/ZGL_cyy/article/details/122836368
為什么使用NIO:因為傳統(tǒng)IO文件傳輸速率低,所以選擇了NIO進行文件的下載操作。NIO還有一個好處就是其中零拷貝可以實現(xiàn)減少內(nèi)存中數(shù)據(jù)的重復,減少CPU操作的效果。所以相對于傳統(tǒng)IO,NIO有著效率高點的優(yōu)勢。

2 NIO為何較傳統(tǒng)的io速度較快

就拿單個io過程來看,首先時間主要花在了用戶態(tài)和內(nèi)核態(tài)的轉換上,其次,考慮將多個io的“合并”為一個io,這不就節(jié)省時間了嗎

相應的NIO主要做了兩方面的提升

1.避免了用戶態(tài)和內(nèi)核態(tài)的交換,直接操作內(nèi)存,用戶態(tài)和內(nèi)核態(tài)的轉換是很費時的,傳統(tǒng)的io寫入磁盤時,用戶態(tài)的接口不能直接操作內(nèi)存,而是通過操作系統(tǒng)調(diào)用內(nèi)核態(tài)接口來進行io。

2.利用buffer減少io的次數(shù),buffer化零為整”的寫入方式因為大大減小了尋址/寫入次數(shù),所以就降低了硬盤的負荷。

3.IO 是基于流來讀取的,而NIO則是基于塊讀取,面向流 的 I/O 系統(tǒng)一次一個字節(jié)地處理數(shù)據(jù)。一個輸入流產(chǎn)生一個字節(jié)的數(shù)據(jù),一個輸出流消費一個字節(jié)的數(shù)據(jù)。為流式數(shù)據(jù)創(chuàng)建過濾器非常容易。鏈接幾個過濾器,以便每個過濾器只負責單個復雜處理機制的一部分,這樣也是相對簡單的。不利的一面是,面向流的 I/O 通常相當慢。
一個 面向塊 的 I/O 系統(tǒng)以塊的形式處理數(shù)據(jù)。每一個操作都在一步中產(chǎn)生或者消費一個數(shù)據(jù)塊。按塊處理數(shù)據(jù)比按(流式的)字節(jié)處理數(shù)據(jù)要快得多。但是面向塊的 I/O 缺少一些面向流的 I/O 所具有的優(yōu)雅性和簡單性。

4.非阻塞IO 和 異步IO的支持, 減少線程占有的??臻g,以及上下文切換

5.IO 多路復用的支持

6.Buffer 支持,所有讀寫操作都是基于 緩沖 來實現(xiàn)

7.NIO 支持 Direct Memory, 可以減少一次數(shù)據(jù)拷貝

8.Netty 零拷貝的支持

3 NIO實戰(zhàn)上傳下載

3.1 url下載文件

java NIO包提供了無緩沖情況下在兩個通道之間直接傳輸字節(jié)的可能。

為了讀來自URL的文件,需從URL流創(chuàng)建ReadableByteChannel :

ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());

從ReadableByteChannel 讀取字節(jié)將被傳輸至FileChannel:

FileOutputStream fileOutputStream = new FileOutputStream(FILE_NAME);
FileChannel fileChannel = fileOutputStream.getChannel();

然后使用transferFrom方法,從ReadableByteChannel 類下載來自URL的字節(jié)傳輸?shù)紽ileChannel:

fileOutputStream.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE);

transferTo() 和 transferFrom() 方法比簡單使用緩存從流中讀更有效。依據(jù)不同的底層操作系統(tǒng),數(shù)據(jù)可以直接從文件系統(tǒng)緩存?zhèn)鬏數(shù)轿覀兊奈募?,而不必將任何字?jié)復制到應用程序內(nèi)存中。

在Linux和UNIX系統(tǒng)上,這些方法使用零拷貝技術,減少了內(nèi)核模式和用戶模式之間的上下文切換次數(shù)。

工具類:

/**NIO文件下載工具類
 * @author olalu
 */
public class NioDownloadUtils {

    /**
     * @description:
     * @param file: 要下在文件
     * @return: void
     */
    public static void downloadDoc(File file,HttpServletResponse response) throws IOException {
        OutputStream outputStream = 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"));
        response.setContentLength((int) file.length());
        //獲取文件輸入流
        FileInputStream fileInputStream = new FileInputStream(file);
        //獲取輸出流通道
        WritableByteChannel writableByteChannel = Channels.newChannel(outputStream);
        FileChannel fileChannel = fileInputStream.getChannel();
        //采用零拷貝的方式實現(xiàn)文件的下載
        fileChannel.transferTo(0,fileChannel.size(),writableByteChannel);
        //關閉對應的資源
        fileChannel.close();
        outputStream.flush();
        writableByteChannel.close();
    }

    public static void downloadDoc(String path,HttpServletResponse response) throws IOException {
        File file = new File(path);
        if (!file.exists()){
            throw new RuntimeException("文件不存在");
        }
        downloadDoc(file,response);
    }

}

3.2 通過NIO上傳文件

/**
     * 文件上傳方法
     */
    public static Result uploading(MultipartFile file) {
        //獲取文件名
        String realName = file.getOriginalFilename();
        String newName = null;
        if(realName != null && realName != ""){
            //獲取文件后綴
            String suffixName = realName.substring(realName.lastIndexOf("."));
            //生成新名字
            newName = UUID.randomUUID().toString().replaceAll("-", "")+suffixName;
        }else {
            return Result.fail("文件名不可為空");
        }
        //創(chuàng)建流
        FileInputStream fis = null;
        FileOutputStream fos = null;
        //創(chuàng)建通道
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            fis = (FileInputStream)file.getInputStream();
            //開始上傳
            fos = new FileOutputStream(UPLOAD_URL+"\\"+newName);
            //通道間傳輸
            inChannel = fis.getChannel();
            outChannel = fos.getChannel();
            //上傳
            inChannel.transferTo(0,inChannel.size(),outChannel);

        }catch (IOException e){
            return Result.fail("文件上傳路徑錯誤");
        }finally {
            //關閉資源
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (inChannel != null) {
                    inChannel.close();
                }
                if (outChannel != null) {
                    outChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.ok(newName);

    }

The above is the detailed content of How does Java use NIO to optimize IO to implement file upload and download functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to iterate over a Map in Java? How to iterate over a Map in Java? Jul 13, 2025 am 02:54 AM

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)-&gt

Java Optional example Java Optional example Jul 12, 2025 am 02:55 AM

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

Comparable vs Comparator in Java Comparable vs Comparator in Java Jul 13, 2025 am 02:31 AM

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

How to fix java.io.NotSerializableException? How to fix java.io.NotSerializableException? Jul 12, 2025 am 03:07 AM

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying

How to handle character encoding issues in Java? How to handle character encoding issues in Java? Jul 13, 2025 am 02:46 AM

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

Comparing Traditional Java IO with New IO (NIO) Comparing Traditional Java IO with New IO (NIO) Jul 13, 2025 am 02:50 AM

Traditional IO is suitable for simple file reading and writing, while NIO is suitable for concurrent and non-blocking scenarios. 1. Traditional IO is blocking stream operation, suitable for small amounts of connections and sequential processing; 2. NIO is based on channels and buffers, supports non-blocking and multiplexing, suitable for high concurrency and random access; 3. NIO can memory map files, improving the processing efficiency of large files; 4. Traditional IO API is simple and easy to use, strong compatibility, and high NIO learning and debugging costs; 5. Choose according to performance requirements, if there is no bottleneck, there is no need to force replacement.

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Java method references explained Java method references explained Jul 12, 2025 am 02:59 AM

Method reference is a way to simplify the writing of Lambda expressions in Java, making the code more concise. It is not a new syntax, but a shortcut to Lambda expressions introduced by Java 8, suitable for the context of functional interfaces. The core is to use existing methods directly as implementations of functional interfaces. For example, System.out::println is equivalent to s->System.out.println(s). There are four main forms of method reference: 1. Static method reference (ClassName::staticMethodName); 2. Instance method reference (binding to a specific object, instance::methodName); 3.

See all articles