I/O in Java

Source: Internet
Author: User
Tags flush

I/O refers to input and output, that is, inputs and outputs, we are talking about I/O in Java, then we are standing in the virtual machine's perspective to see what inputs and outputs. Input can also be called data source side, can think of will have, file, network, console manual input. And the output can also be called the data receiving end, can think of still that several, output to file, network, console.

Well, at the moment just figuring out where the data came from, however, our data interaction is certainly not so simple, we also need to consider a variety of ways to transfer, whether I am a character transmission or byte transmission, or binary transmission, to not buffer access, and so on. In this way, to show that the data transmission can be sure to require a lot of objects.

In order to solve the various data-side and data-interaction methods, Java designers have to avoid designing too many classes (in fact, there are many ...). ) designed the I/O architecture.

First to put the whole picture, this diagram simple but not simple, today I just said that a small part of the things, a lot of implementation of the class have not come out alone said.

First look at the file class, where the file class represents the file name and directory pathname in an abstract way. This class is used primarily for file and directory creation, file lookup, and file deletion. As you can see, the file class, although the name looks like a document, does not, in fact, represent the name of a particular file and the name of a group of files in a directory.

Let's look at an example and feel the use of the File class.

  Public Static voidMain (String args[]) {string DirName= "."; File F1=NewFile (dirname);//current Project Working directory        if(F1.isdirectory ()) {System.out.println ("Directory of" +dirname); String s[]=f1.list ();  for(inti = 0; i < s.length; i++) {File F=NewFile (dirname + "/" +S[i]); if(F.isdirectory ()) {System.out.println (s[i)+ "is a directory"); } Else{System.out.println (s[i]+ "is a file"); }            }        } Else{System.out.println (dirname+ "is not a directory"); }    }

What if I want to read or write to the file? Then it needs to be done with the input and output stream.

First of all, the concept of a dirty stream represents any data source object capable of producing data or a receiving end object capable of receiving data. Focus, flow represents the object. This object has the ability to send or receive data. So the essence of flow is to abstract the data source (data source end, data receiving end) and data transmission (character, byte, binary, etc.) into the result of class. The function is to transfer data.

In the I/O architecture, because there are too many streams to be needed, Java designers avoid designing too many classes, eventually using the decorator pattern to design the entire flow structure, dividing the stream by function, and dynamically assembling the streams to get the desired flow. If you want to get a buffered file input byte stream, you can.

Import Java.io.BufferedInputStream; Import Java.io.FileInputStream; Import Java.io.InputStream;  Public class IOTEST3 {    publicstaticvoidthrows  Exception {         New fileinputstream ("test.txt");         New Bufferedinputstream (FIS);}    }

Stream classification:

    1. The byte stream. InputStream is the base class for all byte input streams, and OutputStream is the base class for all byte output streams.

    2. Character Stream. Reader is the base class for all read string input streams, while Writer is the base class for all output strings.

In addition, Inputstream,outputstream,reader,writer are abstract classes.

Byte stream is the most basic, all the InputStream and OutputStream sub-class are byte stream, mainly used to deal with binary data, it is processed by byte, but the actual number of data is text, so put forward the concept of character stream, it is based on the virtual machine Encode to deal with, That is, the bytes are converted to characters according to the character set. The default encoding in Java is Unicode encoding.

The byte stream and the character stream are associated by inputstreamreader,outputstreamwriter, in fact through byte[] and String. The problem of Chinese characters in the actual development is actually caused by the non-unification between the character stream and the byte stream. When converting from byte to character stream, it is actually byte[] converted to String

byte New byte [Ten= "UTF-8"new String (bytes, charsetname);

There is a key parameter character set encoding, usually we omit it, and when the character is converted into a byte stream, it is actually a string conversion to byte[]

String s = "Hello"; byte [] bytes = S.getbytes ();

For other streams, the main purpose is to improve performance and ease of use, such as:

// byte stream correlation Fileinputstreamfileoutputstreambufferedinputstreambufferedoutputstream // character Stream Correlation Filereaderfilterwriterbufferedreaderbufferedwriter

The difference between a byte stream and a character stream, in addition to the class name, is that the character stream uses the buffer, and the byte stream does not use a buffer.

A buffer can be simply understood as a special memory. In some cases, if a program frequently operates a resource (such as a file or database), the performance is very low, at this point in order to improve performance, you can temporarily read some of the data into the memory of a piece of the area, and then directly from the region to read the data, because the read memory speed will be faster, This can improve the performance of the program.

In a character stream operation, all characters are formed in memory, and all of the content is temporarily stored in memory before output, so buffer staging data is used. You can use the flush () method in the Writer class if you want to output all the contents of a character stream without closing it.

Selection of Byte stream and character stream

The read () method of the Reader class returns the type int, which is the character (two bytes in total 16 bits), the range between 0 and 65535 (0X00-0XFFFF), and returns-1 if the end of the stream has been reached.

The read () method of InputStream also returns int, but since this class is byte-oriented and one bytes is 8 bits, the int byte value in the range 0 to 255 is returned. If no bytes are available since the end of the stream has been reached, the return value-1. Therefore, a value that cannot be represented by 0-255 is read by a character stream, such as a Chinese character.

Characters (Reader and Writer): Chinese, characters are only formed in memory, manipulating characters, arrays of characters, or strings.

Bytes (InputStream and OutputStream): Audio files, pictures, songs, all of the hard disks are saved on the file or when they are transferred, manipulate bytes and byte arrays or binary objects.

Finally, consider an example that implements the copy function. The code is just for demonstration, so it shouldn't be a reasonable notation.

 Public Static voidMain (string[] args)throwsException {File inFile=NewFile ("D:\\input.txt"); File OutFile=NewFile ("D:\\output.txt"); FileInputStream InputStream=NewFileInputStream (InFile); FileOutputStream OutputStream=NewFileOutputStream (OutFile); byte[] content =New byte[1024]; intLen;  while(len = inputstream.read (content))! =-1) {outputstream.write (content,0, Len);    } outputstream.flush ();    Outputstream.close (); Inputstream.close ();}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.