"There are several ways to copy files in Java, which one is the most efficient?"
This question is an interview question for students with 4 years of experience when Jingdong is on the side.
Hi, my name is Mic, a Java programmer who has been working for 14 years.
Regarding the answer to this question, I organized the text version into a 15W word interview document.
You can add V on my homepage to get it.
Check out the experts' answers below.
Expert:
The first is to use the library under the java.io package, use FileInputStream to read, and then use FileOutputStream to write.
The second is to use the library under the java.nio package and use the transferTo or transfFrom method.
Third, the Java standard library itself already provides an implementation of Files.copy.
For the efficiency of Copy, this is actually related to the operating system and configuration. In traditional file IO operations, we all call the underlying standard IO system call functions read() and write() provided by the operating system. The call will cause the current user thread to switch to the kernel state, and then the kernel thread is responsible for reading the corresponding file data into the kernel's IO buffer, and then copying the data from the kernel IO buffer to the process's private address space, and this is done. An IO operation was performed.
The NIO transferTo and transfFrom methods provided in NIO are also known as zero-copy implementations.
It can use the underlying mechanism of modern operating systems to avoid unnecessary copying and context switching, so it performs better in performance.
Summarize
There are quite a lot of questions and contents about file IO. This piece belongs to the basic knowledge in Java, but with the extension of this technical knowledge, it will involve NIO, AIO, zero copy, IO multiplexing mechanism and so on.
For job seekers, the importance of this content is self-evident.
Remember to like and subscribe!
Copyright notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated. Please indicate the source forMic带你学架构
!
If this article is helpful to you, please help to follow and like, your persistence is the driving force for my continuous creation. Welcome to follow the WeChat public account of the same name to get more technical dry goods!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。