Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the methods of writing files?

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "what are the methods of writing files". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. let's follow the editor's way of thinking to study and learn "what are the methods of writing files?"

0. What is stream?

"flow" in Java is an abstract concept and a metaphor, just like water, water flows from one end to the other, while in Java, "flow" is data, which "flows" from one end to the other.

According to the direction of the stream, we can divide the stream into the input stream and the output stream. When the program needs to read data from the data source, it will open an input stream. On the contrary, when the data is written to the destination of a data source, it will also open an output stream. The data source can be a file, memory, network, etc.

1. What is byte flow?

The basic unit of a byte stream is Byte, and a byte is usually 8 bits, which is used to process binary (data). There are two base classes for byte streams: InputStream (input byte stream) and OutputStream (output byte stream).

The inheritance diagram of the common byte flow is shown in the following figure:

Where InputStream is used for read operations and OutputStream for write operations.

two。 What is a character stream?

The basic unit of the character stream is Unicode, with a size of two bytes (Byte), which is usually used to process text data. There are two base classes of character streams: Reader (input character stream) and Writer (output character stream).

The inheritance diagram of the common character stream is shown in the following figure:

3. Classification of streams

Streams can be classified according to different dimensions, for example, according to the direction of the flow, according to the unit of transmission, and according to the function of the flow, such as the following.

① classifies by flow direction

Output stream: OutputStream and Writer are the base classes.

Input stream: InputStream and Reader are the base classes.

② classifies according to transmission data unit

Byte stream: OutputStream and InputStream are the base classes.

Character stream: Writer and Reader are the base classes.

③ is classified by function

Byte stream: you can read and write data from or to a specific place (node).

Processing flow: it is the connection and encapsulation of an existing stream, and the data is read and written through the function call of the encapsulated stream.

PS: we usually classify streams in terms of the units in which data is transmitted.

4. Six ways to write a document

The method of writing a file is mainly derived from the subclass of the character stream Writer and the output byte stream OutputStream, as shown in the following figure:

The above classes marked with ✅ numbers are used to write files. In addition, Files classes are provided in JDK 1.7 to implement various operations on files. Let's look at them separately.

Method 1:FileWriter

FileWriter is a member of the "character stream" system, and it is also the basic class for file writing. It contains five constructors that can pass a specific file location, or File object, the second parameter indicates whether to append the file, and the default value of false means to rewrite the file content, not to append the file content (on how to append the file, we will talk later).

The implementation of the FileWriter class is as follows:

/ * * method 1: use FileWriter to write the file * @ param filepath file directory * @ param content content to be written * @ throws IOException * / public static void fileWriterMethod (String filepath, String content) throws IOException {try (FileWriter fileWriter = new FileWriter (filepath)) {fileWriter.append (content);}}

You only need to pass in the specific file path and the content to be written. The calling code is as follows:

Public static void main (String [] args) {fileWriterMethod ("/ Users/mac/Downloads/io_test/write1.txt", "Hello, Java Chinese community.");}

Then we open the written file and the result is as follows:

On the issue of resource release: in versions above JDK 7, we only need to use try-with-resource to achieve resource release, such as using try (FileWriter fileWriter = new FileWriter (filepath)) {.} to achieve automatic release of FileWriter resources.

Method 2:BufferedWriter

BufferedWriter is also part of the character stream system, and unlike FileWriter, BufferedWriter has its own buffer, so it writes better to files (both will be tested below).

Small knowledge points: buffer zone

A buffer, also known as a cache, is part of the memory space. In other words, a certain amount of storage space is reserved in the memory space, which is used to buffer the input or output data, and this part of the reserved space is called buffer.

Advantages of buffer zone

Take the writing of the file stream as an example, if we do not use buffers, then each write operation CPU will interact with the low-speed storage device, that is, the disk, so the whole speed of writing to the file will be limited by the low-speed storage device (disk). However, if a buffer is used, each write operation will first save the data in the high-speed buffer memory, and when the buffer data reaches a certain threshold, the file will be written to disk at one time. Because the write speed of memory is much faster than that of disk, when there is a buffer, the write speed of files is greatly improved.

After understanding the advantages of the cache, let's go back to the topic of this article, and then we use BufferedWriter to write the file, the implementation code is as follows:

/ * * method 2: use BufferedWriter to write the file * @ param filepath file directory * @ param content content to be written * @ throws IOException * / public static void bufferedWriterMethod (String filepath, String content) throws IOException {try (BufferedWriter bufferedWriter = new BufferedWriter (new FileWriter (filepath) {bufferedWriter.write (content);}}

The calling code is similar to method 1, so I won't repeat it here.

Method 3:PrintWriter

PrintWriter is also a member of the character stream system. Although it is called "character print stream", it can also be used to write files. The implementation code is as follows:

/ * * method 3: use PrintWriter to write the file * @ param filepath file directory * @ param content content to be written * @ throws IOException * / public static void printWriterMethod (String filepath, String content) throws IOException {try (PrintWriter printWriter = new PrintWriter (new FileWriter (filepath) {printWriter.print (content);}}

As you can see from the above code, both PrintWriter and BufferedWriter must be based on the FileWriter class to complete the call.

Method 4:FileOutputStream

The above three examples are about writing a character stream to a file, and then we will use a byte stream to complete the file writing. We will first convert the string to a binary file using the getBytes () method that comes with String, and then write the file. The implementation code is as follows:

/ * * method 4: use FileOutputStream to write the file * @ param filepath file directory * @ param content content to be written * @ throws IOException * / public static void fileOutputStreamMethod (String filepath, String content) throws IOException {try (FileOutputStream fileOutputStream = new FileOutputStream (filepath)) {byte [] bytes = content.getBytes (); fileOutputStream.write (bytes);}}

Method 5:BufferedOutputStream

BufferedOutputStream is a member of the byte stream system. Unlike FileOutputStream, it has its own buffer function, so its performance is better. Its implementation code is as follows:

/ * method 5: use BufferedOutputStream to write the file * @ param filepath file directory * @ param content content to be written * @ throws IOException * / public static void bufferedOutputStreamMethod (String filepath, String content) throws IOException {try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream (new FileOutputStream (filepath) {bufferedOutputStream.write (content.getBytes ());}}

Method 6:Files

The next operation method is different from the previous code, and then we use a new file manipulation class Files provided in JDK 7 to implement file writing.

Files class is a new class added by JDK 7 to manipulate files. It provides a large number of methods for processing files, such as copying, reading, writing, obtaining file attributes, quickly traversing file directories, and so on. These methods greatly facilitate the operation of files. Its implementation code is as follows:

/ * * method 6: use Files to write the file * @ param filepath file directory * @ param content content to be written * @ throws IOException * / public static void filesTest (String filepath, String content) throws IOException {Files.write (Paths.get (filepath), content.getBytes ());}

All of the above methods can be used to write files, but which method has better performance? Next, let's test it.

5. Performance testing

Let's first build a large string, then use the above six methods to test the file writing speed, and finally print out the result. The test code is as follows:

Import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; public class WriteExample {public static void main (String [] args) throws IOException {/ / build writes StringBuilder stringBuilder = new StringBuilder (); for (int I = 0; I < 1000000; iTunes +) {stringBuilder.append ("ABCDEFGHIGKLMNOPQRSEUVWXYZ") } / / write content final String content = stringBuilder.toString (); / / directory where files are stored final String filepath2 = "/ Users/mac/Downloads/io_test/write1.txt"; final String filepath3 = "/ Users/mac/Downloads/io_test/write2.txt"; final String filepath4 = "/ Users/mac/Downloads/io_test/write3.txt" Final String filepath5 = "/ Users/mac/Downloads/io_test/write4.txt"; final String filepath6 = "/ Users/mac/Downloads/io_test/write5.txt"; final String filepath7 = "/ Users/mac/Downloads/io_test/write6.txt"; / / method 1: write the file long stime1 = System.currentTimeMillis () using FileWriter; fileWriterTest (filepath2, content); long etime1 = System.currentTimeMillis () System.out.println ("FileWriter write time:" (etime1-stime1)); / / method 2: write the file long stime2 = System.currentTimeMillis () using BufferedWriter; bufferedWriterTest (filepath3, content); long etime2 = System.currentTimeMillis (); System.out.println ("BufferedWriter write time:" + (etime2-stime2)) / / method 3: use PrintWriter to write file long stime3 = System.currentTimeMillis (); printWriterTest (filepath4, content); long etime3 = System.currentTimeMillis (); System.out.println ("PrintWriterTest write time:" + (etime3-stime3)); / / method 4: use FileOutputStream to write file long stime4 = System.currentTimeMillis (); fileOutputStreamTest (filepath5, content) Long etime4 = System.currentTimeMillis (); System.out.println ("FileOutputStream write time:" + (etime4-stime4)); / / method 5: write the file long stime5 = System.currentTimeMillis () using BufferedOutputStream; bufferedOutputStreamTest (filepath6, content); long etime5 = System.currentTimeMillis (); System.out.println ("BufferedOutputStream write time:" + (etime5-stime5)) / method 6: use Files to write the file long stime6 = System.currentTimeMillis (); filesTest (filepath7, content); long etime6 = System.currentTimeMillis (); System.out.println ("Files write time:" + (etime6-stime6)) Method 6: use Files to write the file * @ param filepath file directory * @ param content content to be written * @ throws IOException * / private static void filesTest (String filepath, String content) throws IOException {Files.write (Paths.get (filepath), content.getBytes ()) Method 5: use BufferedOutputStream to write the file * @ param filepath file directory * @ param content content to be written * @ throws IOException * / private static void bufferedOutputStreamTest (String filepath, String content) throws IOException {try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream (new FileOutputStream (filepath) {bufferedOutputStream.write (content.getBytes ()) Method 4: use FileOutputStream to write the file * @ param filepath file directory * @ param content content to be written * @ throws IOException * / private static void fileOutputStreamTest (String filepath, String content) throws IOException {try (FileOutputStream fileOutputStream = new FileOutputStream (filepath)) {byte [] bytes = content.getBytes () FileOutputStream.write (bytes) Method 3: use PrintWriter to write the file * @ param filepath file directory * @ param content content to be written * @ throws IOException * / private static void printWriterTest (String filepath, String content) throws IOException {try (PrintWriter printWriter = new PrintWriter (new FileWriter (filepath) {printWriter.print (content) Method 2: use BufferedWriter to write the file * @ param filepath file directory * @ param content content to be written * @ throws IOException * / private static void bufferedWriterTest (String filepath, String content) throws IOException {try (BufferedWriter bufferedWriter = new BufferedWriter (new FileWriter (filepath) {bufferedWriter.write (content) Method 1: use FileWriter to write the file * @ param filepath file directory * @ param content content to be written * @ throws IOException * / private static void fileWriterTest (String filepath, String content) throws IOException {try (FileWriter fileWriter = new FileWriter (filepath)) {fileWriter.append (content);}

Before viewing the results, let's go to the corresponding folder to see if the files written are normal, as shown in the following figure:

As can be seen from the above results, each method normally writes 26 MB of data, and the final result of their execution is shown in the following figure:

As can be seen from the above results, the operation speed of character stream is the fastest, because the code we tested operates on strings, so when using byte streams, we need to convert strings to byte streams first, so it does not have an advantage in execution efficiency.

As you can see from the above results, the best performance is the string write stream BufferedWriter with a buffer, and the slowest performance is Files.

PS: the above test results are only valid for string operation scenarios. If you are operating on binary files, you should use byte stream BufferedOutputStream with buffer.

6. Extended knowledge: content addition

The above code will rewrite the file. If you only want to append the content to the original, you need to set an extra parameter of append to true when creating the write stream. For example, if we use FileWriter to append the file, the implementation code is as follows:

The parameter of public static void fileWriterMethod (String filepath, String content) throws IOException {/ / the second append passes a true = the meaning of the appended file try (FileWriter fileWriter = new FileWriter (filepath, true)) {fileWriter.append (content);}}

If you are using BufferedWriter or PrintWriter, you also need to set one more parameter of append to true when building the new FileWriter class. The implementation code is as follows:

Try (BufferedWriter bufferedWriter = new BufferedWriter (new FileWriter (filepath, true) {bufferedWriter.write (content);}

Compared with the Files class, it is more special to implement the additional writing of the file. It needs to pass an extra parameter of StandardOpenOption.APPEND when calling the write method. The implementation code is as follows:

Files.write (Paths.get (filepath), content.getBytes (), StandardOpenOption.APPEND); thank you for reading, these are the contents of "what are the methods of writing files?" after the study of this article, I believe you have a deeper understanding of what the methods of writing files have, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report