Java text file operation method example explanation

This article describes the operation method of Java text file. Share with you for your reference. The specific analysis is as follows:

At first, Java did not support the processing of text files. In order to make up for this shortcoming, two classes, reader and writer, were introduced. These two classes are abstract classes. Write (char [] ch, int off, int length), flush() and close() methods in writer are abstract methods, and read (char [] ch, int length) and close() methods in reader are abstract methods. Subclasses should implement them separately.

When reading and writing text files, it is very convenient to use readers, such as FileReader, inputstreamreader and BufferedReader. The most important class is inputstreamreader, which is a bridge between bytes and characters. You can specify the encoding method in the constructor. If not specified, the default encoding method of the underlying operating system will be adopted, such as GBK. When using FileReader to read files,

The read () method returns the next character to be read. Of course, you can also use read (char [] ch, int length), which is similar to processing binary files. I won't say more. If inputstreamreader is used to read files

This is no different from FileReader. In fact, the methods in FileReader are inherited from inputstreamreader. The read () method is time-consuming. In order to improve efficiency, we can use BufferedReader to wrap the reader, which can improve the reading speed. We can read text line by line and use the readLine () method.

When you understand how to read text files with reader, it is also very simple to write files with writer. It should be noted that when you write a file, in order to improve efficiency, the written data will be put into the buffer first and then written to the file. So sometimes you need to actively call the flush () method. The file writing method corresponding to the above is:

Don't forget to turn off the stream when you're finished! The following is a small example to help novices understand. In fact, sometimes the IO system of Java needs us to remember more, otherwise it will be unfamiliar one day.

I hope this article will be helpful to your Java programming.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>