Detailed explanation of file reading and writing examples of Java programming

This paper describes the method of file reading and writing in Java programming. Share with you for your reference, as follows:

What is the role of file read and write operations in Java?

When answering this question, we should first think that Java is just a language and a tool for us. In this way, the answer is clear, that is, write all kinds of foreign data into a file to save it; Or read the data from the file for our use. In the following movie process, download a movie from network resources, save it on your computer (write a file), and open it with the player (read a file) when you want to see it.

How to read and write files in Java?

First, there are two streams in Java, byte stream and character stream. The two base classes of byte stream are InputStream and OutputStream; The two base classes for character streams are reader and writer. The so-called file stream means that we cannot leave the stream for file operations. It can be seen that a class we want to use must inherit one of the above four base classes. In Java, everything is a class and everything is an object. It's natural to think of the types of file operations:

The following four classes are used directly:

In byte stream: FileInputStream and fileoutputstream; in character stream: FileReader and filewriter

Just find the class. The rest is to find an implementation method.

There are two options here, which involves how to choose the appropriate file reading and writing method?

Differences in selection criteria:

Reading files in bytes is often used to read binary files, such as pictures, sounds, images and so on. Read files in character units, often used to read text, numbers and other types of files Whether to use buffer to encapsulate the file input / output stream depends on the size of the file. If a large file is read and written, select buffer to provide file reading and writing efficiency.

The following is a simple application example:

1. Use byte stream to read and write files directly:

Note: fileoutputstream (file, true); The true parameter means that the original file will not be overwritten, and the content will be added directly after the file.

2. Use character stream to read and write files directly:

Application of file read / write stream encapsulated with buffer:

1. Read and write the file after encapsulating the byte stream:

2. Read and write the file after encapsulating the character stream:

I hope this article will be helpful to you in 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
分享
二维码
< <上一篇
下一篇>>