Java input and output streams Comments

Java input and output streams Comments

references

https://docs.oracle.com/javase/tutorial/essential/io/streams.html

Explain in great detail, it is easy to understand.

I/O Streams

An IO stream represents an input source or output destination. A stream can represent many different kinds of sources, it can also represent different kinds of destinations.

What does this mean?
Yucheng Lin: the source can be a disk file, device (for example, the console), and other programs such as a memory array. This is called the different types of sources. The destination can also be a disk file, device, and other programs such as data memory, which is called different types of output destinations.

Streaming support different types of data, including the type byte, the basic data types, and other objects. Some only pure stream of data sent over, and some of the data stream may be some conversions.

For example, BufferReader read, PrintWriter.println (data) will be at the end of the data line with a line terminator line.

No matter how the internal flow of work, All Present STREAMS The Same Simple Model to Programs that use Them; stream is a sequence of data A program uses an input stream to read data from a source, one item at a time..

Yucheng Lin: You can imagine the flow of water pipes, water pipes can transport data to the destination. The input stream, the output stream is flowing from the source data from the data source to the program. Input and output are relative to the program.

Here Insert Picture Description

A program uses an output stream to write data to a destination, one item at a time.
Here Insert Picture Description

So the key issue is that we want to know who is the data source in the end! Because one is program, the other is a data source.

Stream can handle a variety of data, from basic to advanced object types, all can handle the flow.

Yes, the byte, to the character, to the line, process flow are possible, including the output format, the stream can all be determined. Now do not understand all right, look back

We know enough, but also know the concept of a byte stream and character stream, because we know that the concept of a byte stream and character stream, you will be able to better understand the reader and writer.

Really complicated! Take your time, come on!

Stream of bytes (byte stream)

Byte stream using the program to perform 8-bit byte input and output. All his streams are inherited InputStream and OutputStream

There are several classes byte stream, byte stream to demonstrate how it works, we are concerned about IO byte stream file. The FileInputStream and a FileOutputStream , other types of substantially byte stream is so used, They differ mainly in the way they are constructed.

It is different from the time of creation, so when you create, and was forced to rip off a year when the Council can look at the constructor of this flow is like, for example, BufferedReader constructor arguments must be of type Reader, so You can use InputStreamReader to convert.

A byte stream

We will explore FileInputStream and FileOutputSteam,

How to explore?

For example, look at the following java program, which is a xanadu.txt already created a text file, outagain.txt is a text file, the file name is to be output, this file can be created ahead of time, you can not create in advance, If the advance is not created, the program will create for us, then write the data to the newly created file.
CopyBytes.java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyBytes {
    public static void main(String[] args) throws IOException {
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream("xanadu.txt");
            out = new FileOutputStream("outagain.txt");
            int c;
            while ((c = in.read()) != -1) { // 读取的都是ASCII值,(一次读取一个字节,8bit,一个英文字母占一个字节,一个中分字符占2个字节,例如,如果xanadu.txt文件的内容是abde, 则c这个变量每次循环得到的值分别是97,98,100,101,不信的话你可以打印看一下)
                out.write(c);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}

Look below this figure just fine.
Here Insert Picture Description
Note that when we do not use a stream, we must close the flow, otherwise it could cause serious resource leaks.

Yes, different times to close the tap
point, byte stream file I explain clearly.

Well, what we do not use the byte stream it?

It seems that byte stream of the program we have just written in a very easy to use, but very bottom.

What is the very bottom?
Yucheng Lin: We direct operation is a byte

Since xanadu.txt contains the character data, so the best way is to use a character stream. Then we'll discuss character stream. Of course, there are more flows for more complicated data types. Byte stream should only be used for the basic input / output.

Jifuryu

The Java platform stores character values using Unicode conventions. 字符流IO translates this internal format to and from the local character set.

What is unicode convention?
Yucheng Lin: temporarily Research

In Western countries, the local character set is usually an 8-bit superset of ASCII.

For most applications, the character stream IO IO is not more complicated than byte stream. Use stream classes for input and output are automatically converted into local character set. A program that uses character streams in place of byte streams automatically adapts to the local character set and is ready for internationalization.
Stuff like transforming our programmers do not have to worry about.

If things are not the primary consideration international, you can directly use the character stream classes, no need to worry about the problem of character sets. If internationalization is a matter to be considered, you may need to make very minor adjustments.

A big problem

With a character stream

All character stream classes are inherited from Reader and Writer.
As with the byte stream, there are some character stream classes focus on file IO:. FileReader and FileWriter following example illustrates this CopyCharacters on how to use these classes.

CopyCharacters.java

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyCharacters {
    public static void main(String[] args) throws IOException {
        FileReader inputStream = null;
        FileWriter outputStream = null;
        try {
            inputStream = new FileReader("xanadu.txt");
            outputStream = new FileWriter("characteroutput.txt");
            int c;
            while ((c = inputStream.read()) != -1) {
                outputStream.write(c);
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}

CopyCharacters and CopyBytes these two documents are similar.
Note that, although the use CopyBytes and CopyCharacters int variables are read from the file, however, in CopyCharacters, The variable int holds A Character value in ITS Last 16 bits (two bytes), in CopyBytes, the int variable A holds byte value in ITS Last . 8 bits .

Character Streams that Use Byte Streams

Character stream often wrapper byte stream. When the character stream between characters and byte conversion process, the character stream with a byte stream to implement specific IO. For example, FileReader using FileInputStream, FileWriter uses FileOutputStream.

Yucheng Lin: It means that you use a character stream, you only need to focus on character, because this level byte by byte stream things like character stream to wrap the tube, you do not have control.

There are two special byte-to-character "bridge" steams: InputStreamReader and OutputStreamReader When one byte stream does not yet have a good package character stream classes InputStreamReader and OutputStreamReader to create a stream of characters we meet the need.

FileReader FileInputStream is already packaged character stream, FileWriter FileOutputStream is already packaged character stream.

Line-Oriented IO

What, is not that good character stream is a stream of bytes, how suddenly come to a row-level IO, you are what strange?

Since there is, then there he was useful place to look

Characters in the I / O usually Occurs in Bigger Units Within last SINGLE characters . One of the most common unit is the line. a string of characters with a line terminator at the end.

A line terminator can be a carriage-return / line-feed sequence ( "\ r \ n), a single carriage-return (" \ r ") or a single line-feed (" \ r "). Assumes all possible line terminators application to read a text file, created on any of widely used operating systems.

Let's amend CopyCharacters this example, we use a line-oriented I / O To do this, we must use two classes we have not seen before:

  1. BufferedReader
  2. PrintWriter

We will explain in depth Buffered I / O and Formatting in.

You will explain, I would not necessarily behold

Now, we / O are only interested in their line-oriented I.

Yes, now we are only interested in your part, Oh

CopyLines.java

import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;

public class CopyLines {
    public static void main(String[] args) throws IOException {
        BufferedReader inputStream = null;
        PrintWriter outputStream = null;
        try {
            inputStream = new BufferedReader(new FileReader("xanadu.txt"));
            outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));
            String l;
            while ((l = inputStream.readLine()) != null) {
                outputStream.println(l);
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}

Yes, that English is not the same, more and more interesting.

Invokes the BufferedReader the readLine Returns Line A of The Line with text. PrintWritter using println output, which appends the line terminator for the current operating system. The line terminator and row may be input file is not the same terminator.

Nothing wrong with the operating system is not the same, file terminator is not the same.

Ways to are MANY There Structure text the INPUT and the Output Beyond characters and Lines.
My next lesson will explain this!

Want to learn more, click https://docs.oracle.com/javase/tutorial/essential/io/scanfor.html

OK! For java input stream and output streams be thoroughly get to know! At least in the introductory phase is get to the root.

Guess you like

Origin blog.csdn.net/ChenglinBen/article/details/91127877