IO Review Notes

Source: Internet
Author: User
Tags ranges

1. Operation file:

1). Write: FileOutputStream or FileWriter

2). READ: FileInputStream or FileReader

3). Random Read/write: Randomaccessfile

4). File Properties: Files

2. create the pipeline through PipedOutputStream and PipedInputStream in Java IO. A pipedinputstream stream should be associated with a pipedoutputstream stream. A thread writes through PipedOutputStream

Data can be read by another thread through the associated PipedInputStream.

How to Relate:

1). PipedOutputStream fos = new PipedOutputStream ();

PipedInputStream fis = new PipedInputStream ();

2). Fis.connect (FOS);

3). Fos.connect (FIS);

3. Remember that when you use two associated pipe flows, be sure to assign them to different threads. The read () method and the Write () method call can cause a stream to block, which means that if you try to read and write at the same time in one thread, it can cause thread deadlock.

4. read the data from the array using Bytearrayinputstream or CharArrayReader encapsulated byte or character array. You can also write data to Bytearrayoutputstream or Chararraywriter.

5. system.in, System.out, system.err These 3 streams are also common data sources and data flow destinations. The JVM starts by initializing these 3 streams through the Java runtime, so you don't need to initialize them (although you can replace them at run time).

6. Some implementations like the Pushbackinputstream stream allow you to re-push the data back into the stream for re-reading. However, you can only push a limited amount of data back into the flow, and you cannot read the data as you would an array of operations. The data in the stream can only be accessed sequentially.

7. byte streams are usually named "stream", such as InputStream and OutputStream. In addition to DataInputStream and DataOutputStream are able to read and write int, long, float, and double values, other streams can only be in one operation time

reads or writes a raw byte. character flow is often named "Reader" or "Writer". Character streams are able to read characters (such as Latin1 or Unicode character). (not necessarily two bytes)

8. the Java io stream is a stream of data that can be read from or written to. As mentioned earlier in this series of tutorials, the regular flow is associated with data sources, data flows to destinations, such as files, networks, and so on.

9. Note that the read () method of InputStream returns a byte, meaning that the return value ranges from 0 to 255 (when the end of the stream is reached, 1 is returned), and the Read () method of reader returns a character, This means that the return value ranges from 0 to 65535.

(also returns-1 when the end of the stream is reached). This does not mean that Reade only reads 2 bytes at a time from the data source, and reader reads one or more bytes at a time based on the encoding of the text.

A reader can be combined with a inputstream. If you have a InputStream input stream and want to read the characters from it, you can wrap the InputStream into InputStreamReader. Pass the InputStream to

In the InputStreamReader constructor:

Reader reader = new InputStreamReader (InputStream);

You can specify the decoding method in the constructor.

One . similar to reader and InputStream, a writer can be combined with a outputstream. Wrap the OutputStream into the OutputStreamWriter, and all characters written to OutputStreamWriter will be passed to OutputStream.

This is an example of a outputstreamwriter:

Writer writer = new OutputStreamWriter (outputstream);

Stream with reader and writer at the end of use, you need to close them correctly. This can be achieved by calling the close () method. What happens if the code becomes an exception? Yes, this InputStream object will not be closed.

Try-with-resources .

In Java 7 You can write the code from the example above using the Try-with-resource construct like this:

private static void PrintFileJava7 () throws IOException {

Try (fileinputstream input = new FileInputStream ("file.txt")) {

int data = Input.read ();

while (Data! =-1) {

System.out.print ((char) data);

data = Input.read ();

}

}

}

if the Read () method returns 1, it means that the program has read to the end of the stream, and there is no more data available to read in the stream. 1 is an int type, not a byte or char type, which is not the same. When the end of the stream is reached, you can close the stream.

InputStream contains 2 read () Methods for reading data from the InputStream and storing the data in a buffered array, respectively:

int read (byte[])

int read (byte, int offset, int length)

It is much faster to read one byte array at a time than to read one byte at a time, so use these two methods instead of the read () method whenever possible.

The . Write (Byte) method is used to write a single byte to the output stream. The Write (byte) method of OutputStream writes an int variable containing the data to be written as a parameter. Only the first byte of the int type is written, and the remaining bits are ignored. (Translator Note: Write low 8-bit, ignoring high 24-bit).

OutputStream also contains methods to write all or part of the data in the byte data to the output stream, respectively, write (byte[]) and write (byte[], int offset, int length).

Write (byte[]) writes all the data in the byte array to the output stream.

Write (byte[], int offset, int length) starts from the offset position in the byte data, and the length byte of the data is written to the output stream.

The Flush () method of OutputStream flushes all data written to outputstream into the corresponding target medium. For example, if the output stream is FileOutputStream, then the data written to it may not actually be written to disk.

Even if all the data is written to FileOutputStream, it is possible that the data will remain in the buffer of memory. By calling the flush () method, the data in the buffer can be flushed to disk (or network, and any other form of target medium).

When you create a fileoutputstream that points to an existing file, you can choose to overwrite the entire file or append the content to the end of the file. Different purposes can be achieved by using different constructors.

Randomaccessfile allows you to read and write files back and forth, or to replace portions of the file. FileInputStream and FileOutputStream do not have such a function. Create a randomaccessfile before you use Randomaccessfile,

It must be initialized. Here is an example:

Randomaccessfile file = new Randomaccessfile ("C:\\data\\file.txt", "RW");

Notice the second parameter of the constructor: "RW", which indicates that you open the file as read-write. Check out the Java documentation to learn how you need to construct randomaccessfile.

Read and write back and forth in the randomaccessfile. Before you read or write to a location in Randomaccessfile, you must point the file pointer to that location. This goal can be achieved through the seek () method. You can get the position of the current file pointer by calling Getfilepointer ().

File: Detect the existence of files, file length, rename or move files, delete files, detect whether a path is a file or a directory, read a list of files in a directory

Bytearrayinputstream allows you to read byte stream data from an array of bytes. Bytearrayoutputstream allows you to get the data written to the output stream as an array.

Bufferedinputstream can provide buffers for input streams, which can increase the speed of many IO. You can read a chunk of data at a time without having to read one byte at a time from the network or disk. Especially when accessing large volumes of disk data,

buffering usually makes IO much faster. You can pass a value to the Bufferedinputstream constructor, setting the size of the buffer setting used internally (Translator Note: Default buffer size 8 * 1024B), just like this:

InputStream input = new Bufferedinputstream (New FileInputStream ("C:\\data\\input-file.txt"), 8 * 1024);

This example sets a buffer of 8KB. It is best to set the buffer size to an integer multiple of 1024 bytes, which makes it more efficient to utilize the disk with the built-in buffers.

Bufferedoutputstream can provide buffers for the output stream. You can construct a bufferedoutputstream that uses the default size buffer (Translator Note: Default buffer size 8 * 1024B), or you can manually set the buffer size as follows:

OutputStream output = new Bufferedoutputstream (New FileOutputStream ("C:\\data\\output-file.txt"), 8 * 1024);

To better use the disk with built-in buffers, it is also recommended to set the buffer size to an integer multiple of 1024. The Manual Flush () method is required to ensure that data written to this output stream is actually written to the disk or network.

DataInputStream allows you to read Java base type data from the input stream without having to read byte data every time. You can wrap the InputStream into a datainputstream, and then you can read the base type data from this input stream.

DataOutputStream can write Java basic type data to the output stream

If you want a class to be serializable and deserialized, you must implement the Serializable interface.

ObjectInputStream allows you to read Java objects from the input stream without having to read one byte at a time. You can wrap the InputStream into a objectinputstream, then you can read the object from it, and then cast it to the corresponding type.

ObjectOutputStream allows you to write objects to the output stream without having to write to one byte at a time. You can wrap the outputstream in a objectoutputstream, and then you can write the object to the output stream.

Intra - Java uses UTF8 encoding to represent strings. One byte in the input stream may not be the same as a UTF8 character. If you read UTF8 encoded text in bytes from the input stream, and try to convert the bytes read to characters,

You may not get the results you expect.

the Write (int c) method of writer writes the low 16 bits of the passed-in parameter to writer, ignoring the high 16-bit data.

InputStreamReader and OutputStreamWriter, these two classes convert bytes into character streams, in the middle of the conversion of data, similar to the idea of adapter mode.

InputStreamReader also has other optional constructors that allow you to specify the stream of characters that the underlying stream of bytes will be interpreted as encoded. The OutputStreamWriter also has a constructor that converts the output byte flow into a character stream of the specified encoding.

FileReader has other optional constructors that allow you to read files in different ways, and see the official documentation for more information. FileReader will assume that you want to use the default encoding of the JVM you are using to handle the byte stream, but this is usually not what you want,

you can set the encoding scheme manually. If you want to explicitly specify an encoding scheme, use InputStreamReader with FileInputStream to replace FileReader (translator Note: FileReader has no constructor to specify the encoding). InputStreamReader can

to let you set the encoding processing from the bytes read in the underlying file. One problem with working with files is whether the data currently being written overwrites the original file content or appends to the end of the file. After you create a filewriter, you can implement it by using different constructors

For your different purposes.

BufferedReader, BufferedWriter

Pushbackinputstream,sequenceinputstream,printstream,pushbackreader,linenumberreader, Streamtokenizer,printwriter,stringreader,stringwriter

LineNumberReader is the BufferedReader that records the data line numbers that have been read. By default, the line number starts at 0 and the line number is incremented when LineNumberReader reads to the line terminator. You can get the current line number by using the Getlinenumber () method.

The current number of rows is set by the Setlinenumber () method. Etlinenumber () only changes the value of the variable in the record line number within the LineNumberReader, and does not change the current stream's read position. Stream reads are still sequential, meaning you can't pass

Setlinenumber () to implement a skip read of the stream

Streamtokenizer can recognize identifiers, numbers, quoted strings, and various annotation types. You can also specify what characters are interpreted as spaces, the start and end of comments, and so on. All functions can be configured before Streamtokenizer begins parsing.

StringReader can convert the original string to Reader:reader Reader = new StringReader ("Input string ...");

StringWriter can get the data written to it from writer in the form of a string:

StringWriter writer = new StringWriter ();

String data = writer.tostring ();

StringBuffer DataBuffer = Writer.getbuffer ();  


IO Review Notes

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.