[Java development path] (8) input stream and output stream

Source: Internet
Author: User

[Java development path] (8) input stream and output stream

1. Java stream classificationBy flow direction: input stream: the object that can read a byte sequence from it is called the input stream. Output stream: the object that can write a byte sequence to it is called the output stream. The source and destination of these byte sequences can be files, but they can also be network connections or even memory blocks. The abstract classes InputStream and OutputStream form the basis of the input and output class layer structure. By data transmission unit: byte stream: byte streams for data transmission by function: node streams: stream filtering flow for direct operation on the target device: it is a link and encapsulation of an existing stream. It provides a powerful and flexible read/write function for the program by processing data.2. read/write bytes (InputStream and OutputStream) (1) the InputStream class has an abstract method:

 
abstract int read()This method reads one byte and returns the read bytes, or returns-1 at the end of the Input Source. When designing a specific input stream, you must override this method to provide applicable functions. For example, in the FileInputStream class, this method reads a byte from a file. The InputStream class also has several non-abstract methods that can be read into a byte array or skip a large number of bytes. These methods call abstract read methods, so each subclass only needs to override one method. (2) The OutputStream class defines the following Abstract METHODS: 
 
abstract void write(int b)It can write a byte to an output location. (3) The read and write methods are blocked during execution until the bytes are read or written. This means that if the stream cannot be accessed immediately (usually because the network connection is busy), the current thread will be blocked. This allows other threads to execute useful work during the time when the two methods wait for the specified stream to become available. When you complete stream read/write, you should call the close method to close it. This call will release very limited operating system resources. If an application opens too many streams but does not close them, system resources will be exhausted. When an output stream is closed, the buffer used for the output stream is washed out: all data is temporarily placed in the buffer zone, so that characters transmitted in the form of a larger package will be sent when the output stream is closed. If the file is not closed, the last packet of the written bytes may never be passed. We can use the flush method to extract these outputs. Even if a stream class provides some specific methods using the native read and write Functions, application system programmers seldom use them, because the data that you are interested in may contain numbers, string and object, rather than native bytes. Java provides a number of Classes exported from the basic InputStream and OutputStream classes. These classes allow us to process data in common formats, not just bytes. 
3. Stream familyThe members in the stream family are divided according to their usage, forming two separate layers for processing bytes and characters. In Java, the character adopts the Unicode standard. A character is a 16-bit character, that is, a character is expressed in two bytes. Therefore, the callback stream is introduced in JAVA. The java. io package contains all classes required for stream I/O. There are four basic classes in the java. io package: InputStream, OutputStream, Reader, and Writer. They process byte streams and bytes streams respectively. 
Input/Output Byte stream Ghost stream
Input stream InputStream Reader
Output stream OutputStream Writer
Byte: InputStream and OutputStream read and write the list of bytes or byte arrays. To read and write strings and numbers, you need more powerful sub-classes. For example, DataInputStream and DataOutputStream can read and write all basic Java types in binary format. Character: for Unicode text, sub-classes of the abstract class Reader and Writer can be used. The basic methods of Reader and Writer classes are similar to those in InputStream and OutputStream. 4-byte stream InputStream and OutputStream4.1 InputStream abstract class InputStream is a byte input stream. It is an abstract class and must rely on its subclass to implement various functions. This abstract class is a super class that represents all classes of the byte input stream. Streams inherited from InputStream are all input data to the program, and the data unit is 8 bits. InputStream is the class used to input byte data, therefore, the InputStream class provides three overloaded read methods. Common methods in the Inputstream class:
Common Methods Description
Public abstract int read () Read the next byte of data from the input stream. The returned byte is expressed by the int type value (0-255) supplemented with a high value of 0. If the returned value is-1, no Bytes are read, and the input stream ends.
Public int read (byte B []) Read data of bytes B. length from the input stream and put it in the byte array B. The returned value is the number of bytes read. If the length of the byte array is 0, no bytes of data are read and 0 is returned. Otherwise, at least one byte of data is read. If no byte data is obtained,-1 is returned when the stream reaches the end of the file. The first read byte is stored in B [0], and so on.
Public int read (byte B [], int off, int len) Read data of up to len bytes from the input stream and put it in byte array B. The returned value is the actual number of bytes read. If the length of the byte array is 0, no bytes of data are read and 0 is returned. Otherwise, at least one byte of data is read. If no byte data is obtained,-1 is returned when the stream reaches the end of the file. The first read byte is stored in B [off], the next one is stored in B [off + 1], and so on.
Public int available () Returns the number of bytes that can be read from the input stream. Note: If the input is blocked, the current thread will be suspended. If the InputStream object calls this method, it will only return 0. This method must be called by a subclass object inheriting the InputStream class. Note: although many InputStream implementation classes can correctly return the total number of bytes of the input stream, not all of them can be used. Therefore, it is not correct to use the return value of this method to allocate the byte size to accommodate all the data in the input stream.
Public long skip (long n) N bytes in the input stream are ignored. The returned value is the number of bytes actually ignored. If the value is negative, no bytes of data are skipped.
Public int close () Close the input stream and release the system resources allocated to the input stream.
InputStream subclass: InputStream is used to represent classes that generate input from different data sources. These data sources include:
  • Byte array
  • String object
  • File
  • "Pipeline" is similar to the actual pipeline. It enters from one end and outputs from one end.
  • A sequence composed of other types of streams, so that we can collect them and merge them into a stream. Each data source has an InputStream subclass. In addition, FilterInputStream is also an InputStream that provides a base class for the "decorator" class. The "decorator" class can connect attributes or useful interfaces with the input stream.
Class Function
ByteArrayInputStream Allow using the buffer in the memory as InputStream
StringBufferInputStream Convert String to InputStream
FileInputStream Used to read information from a file
PipedInputStream Generate the data used to write the relevant PipedOutputStream. Implement the concept of "Pipeline.
SequenceInputStream Converts two or more InputStream objects to a single InputStream.
FilterInputStream Abstract class, used as an interface for "decorator. The decorator provides useful functions for other InputStream classes.
4.2 OutputSream abstract class OutputStream provides three write methods for data output, which corresponds to InputStream.
Common Methods Description
Public abstract void write (int B) Writes specified bytes to the output stream. Generally, the lower eight bits (one byte) of parameter B are written to the output stream. The 8-digit height of B is ignored.
Public void write (byte [] B) Write B. length bytes to the output stream from byte array B.
Public void write (byte [] B, int off, int len) Write len bytes of data to the output stream starting from the offset of byte array B to off. B [off] is the first byte to be written, and B [off + len-1] is the last byte to be written. If B is null, an NullPointer exception is thrown. If off or len is a negative number, or off + len is longer than byte array B, an IndexOutOfBoundsException exception is thrown.
Public void flush () Clear the output stream and forcibly write all buffered output bytes.
Public void close () Close the output stream and release the system resources allocated to the output stream.
Subclass of OutputStream: The Class determines the target of the output: byte array (but not a String, but you can use byte array to create it yourself), file or pipeline.
Class Function
ByteArrayOutputStream Create a buffer in the memory. All data sent to the "stream" must be placed in this buffer zone.
FileOutputStream Used to write information to a file.
PipedOutputStream Any information written into it is automatically output as PipedInputStream. Implement the concept of "Pipeline.
FilterOutputStream Abstract class, used as an interface for "decorator. The decorator provides useful functions for other OutputStream classes.
  5. Reader and WriterWhen we first see the Reader and Writer classes, we may think that these two classes are used to replace InputStream and OutputStream, but they are not. Although some original "stream" class libraries are no longer used (if they are used, the compiler will receive a warning ), however, InputStream and OutputStream provide valuable functions in the form of byte stream IO. Reader and Writer provide Unicode and character-oriented I/O functions. Sometimes we use classes in the "Byte" Hierarchy together with classes in the "character" hierarchy. To achieve this goal, we need to use the "adapter" (adapter) Class: InputStreamReader can convert InputStream to Reader, while OutputStream can convert OutputStream to Writer. Reader and Writer inheritance hierarchies are designed to be internationalized. The old IO stream inheritance hierarchy can only support 8-bit streams, and cannot properly process 16-bit Unicode characters. It is designed to support Unicode in all IO operations. Subclass of Reader: subclass of Writer: 6. FileInputStream and FileOutputStream6.1 FileInputStream obtains the input bytes from a file in the file system. (1) constructor
Constructor Description
FileInputStream (String name) Create a FileInputStream object using the path name specified by the name string
FileInputStream (File file) Create a FileInputStream object using a file with the specified path name of the file object
 
 
// FileInputStream(String name) 
String path = "D:\\Recommended system.txt"; 
FileInputStream stream = new FileInputStream(path);  
// FileInputStream(File file) 
File file = new File(path); 
FileInputStream stream2 = new FileInputStream(file);(2) It is used to read original byte streams such as data. (To read the shard stream, consider using FileReader) 

It contains other input streams, which are used as their basic data sources and can directly transmit data or provide some additional functions.
The class itself simply overrides all the methods that pass all requests to the InputStream containing the input stream.
Its subclass can further override some methods in these methods and provide some additional methods and fields. (3) Instances
 
package com.qunar.io;  
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException;  
public class IOUtil {  
public static void main(String[] args) { 
try { 
String path = "D:\\demo.txt"; 
FileInputStream stream = new FileInputStream(path); 
int num = 100; 
byte[] buff = new byte[num]; 
while((stream.read(buff,0,num)) != -1){ 
System.out.println("NewLine->"+new String(buff)); 
}//while 
stream.close(); 
} catch (FileNotFoundException e) { 
e.printStackTrace(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
}Running result: 

NewLine-> My father was a self-taught mandolin player. he was one of the best string instrument players in ourNewLine-> town. he cocould not read music, but if he heard a tune a few times, he cocould play it. when he was yoNewLine-> unger, he was a member of a small country music band. they wocould play at local dances and on aNewLine-> ccasions wocould play for the local radio station. he often told us how he had auditioned and earned aNewLine-> position in a band that featured Patsy Cline as their lead singer. he told the family that after heNewLine-> was hired he never went back. dad was a very religious man. he stated that there was a lot of drinkNewLine-> ing and cursing the day of his audition and he did not want to be around that type of environment. nk
6.2 FileOutputStream (1) constructor
Constructor Description
FileOutputStream (String name) Create a new file output stream using the file with the path specified by the name string.
FileOutputStream (String name, boolean append) Create a new file output stream using the file with the path specified by the name string. If the append parameter is true, the data is added to the end of the file, and existing files with the same name are not deleted (data is added at the end ); otherwise, this method deletes all existing files with the same name.
FileOutputStream (File file) Create a new file output stream using the file with the specified path name of the file object.
FileOutputStream (File file, boolean append) Create a new file output stream using the file with the specified path name of the file object. If the append parameter is true, the data is added to the end of the file, and existing files with the same name are not deleted (data is added at the end ); otherwise, this method deletes all existing files with the same name.
(2) Case studies
 
package com.qunar.io;  
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException;  
public class IOUtil {  
public static void main(String[] args) { 
try { 
String path = "D:\\from.txt"; 
String path2 = "D:\\to.txt"; 
FileInputStream inputStream = new FileInputStream(path); 
FileOutputStream outputStream = new FileOutputStream(path2); 
int num = 100; 
byte[] buff = new byte[num]; 
// Write data from files to memory 
while((inputStream.read(buff,0,num)) != -1){ 
// Write data from memory to files 
outputStream.write(buff); 
}//while 
inputStream.close(); 
outputStream.close(); 
} catch (FileNotFoundException e) { 
e.printStackTrace(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
}  
7. DataInputStream and DataOutputStreamDataInputStream and DataOutputStream are extensions of streaming, making it easier to operate on the Basic Java data types. The data input stream allows applications to read Basic Java data types from the underlying input stream in a machine-independent manner. 
 
package com.qunar.io;  
import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException;  
public class IOUtil {  
public static void main(String[] args) { 
try { 
String path = "D:\\to.txt";  
// Write to a file 
FileOutputStream outputStream = new FileOutputStream(path); 
DataOutputStream dataOutputStream = new DataOutputStream(outputStream); 
// Write an Int value to the file 
dataOutputStream.writeInt(10); 
// Write a Double value to the file 
dataOutputStream.writeDouble(0.98); 
// Write a Long value to the file 
dataOutputStream.writeLong(12l); 
// Write a UTF-8 encoding value into the file 
DataOutputStream. writeUTF ("I'm from Xi'an University of electronic science and technology ");  
// Read from a file 
FileInputStream inputStream = new FileInputStream(path); 
DataInputStream dataInputStream = new DataInputStream(inputStream); 
// Read an Int value from the file 
System. out. println ("read an Int value from the file:" + dataInputStream. readInt ()); 
// Read a Double value from the file 
System. out. println ("read a Double value from the file:" + dataInputStream. readDouble ()); 
// Read a Long value from the object 
System. out. println ("read a Long value from the file:" + dataInputStream. readLong ()); 
// Read a UTF-8 encoded value from the file 
System. out. println ("read an UTF-8 encoded value from the file:" + dataInputStream. readUTF ()); 
} catch (FileNotFoundException e) { 
e.printStackTrace(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
}Running result: 

Read an Int value from the file: 10 read a Double value from the file: 0.98 read a Long value from the file: 12 read a UTF-8 encoded value from the file: i'm from Xi'an University of Electronic Science and Technology
I am a newbie. I don't want to spray it. If you have any questions, please leave a message ....

Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

11.11 Big Sale for Cloud

Get Unbeatable Offers with up to 90% Off,Oct.24-Nov.13 (UTC+8)

Get It Now >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.