Dark Horse programmer-io Other stream objects in the package

Source: Internet
Author: User

--java Training, Android training, iOS training,. NET training, look forward to communicating with you! ——-
There are four main systems in the IO stream:
Character streams: Reader and Writer
BYTE stream: InputStream and Outputsream
Based on these four systems, many objects are derived from the IO stream, the common ones are filereader,filewriter,fileinputstream,fileoutputstream,bufferedinputstream and so on.
In addition to this, there are other common objects that are more specific and often targeted at specific functions. The stream object that we can associate with the file in the application is an important stream object.
Here are the following:
1. Print Flow: PrintWriter and PrintStream
2. Sequence Flow: Sequenceinputstream
3. Flow of operands: ObjectInputStream and ObjectOutputStream
4. Pipe flow: PipedInputStream and PipedOutputStream
5. Random Read and write files: randomaccessfile
6. Manipulating streams of basic data types: DataInputStream and DataOutputStream
7. Manipulating the stream of byte arrays: Bytearrayinputstream and Bytearrayoutputstream
8. Manipulating the flow of character arrays: CharArrayReader and Chararraywriter
9. Flow of manipulating strings: StringReader and StringWriter
First, PrintStream and PrintWriter
These two stream objects can manipulate the input stream and the file directly
PrintStream adds functionality to other output streams, making it easy to print a variety of data that is worth expressing, and PrintStream never throws IOException, which has the print () and println () methods to manipulate the underlying data types. The data is guaranteed to be printed out with the data intact.
The types of arguments that PrintStream constructors can receive are:
1.File object: File
2. String path: String
3. Byte output stream: OutputStream
PrintWriter is a common print stream, especially in web development.
The types of parameters that the PrintWriter constructor can receive are:
1.File object: File
2. String path: String
3. Byte output stream: OutputStream
4. Character output stream: Writer
Example:

 Public classPrintstreamdemo { Public Static void Main(string[] args) {BufferedReader BUFR =NewBufferedReader (NewInputStreamReader (System.inch)); PrintWriter out=NewPrintWriter (System. out,true); String line =NULL;Try{ while((Line=bufr.readline ())! =NULL){ out. println (Line.touppercase ()); }            }Catch(IOException e)            {E.printstacktrace (); } out. Close ();Try{Bufr.close (); }Catch(IOException e)            {E.printstacktrace (); }    }}

PrintWriter Save the data to a file:
PrintWriter out = new PrintWriter ("A.txt");
PrintWriter out = new PrintWriter (New FileWriter ("A.txt"), true);//true indicates automatic refresh
PrintWriter out = new PrintWriter (New BufferedWriter (
New FileWriter ("A.txt"), true);
Second, Sequenceinputstream
Sequenceinputstream can be combined with multiple streams.
Sequenceinputstream represents the logical concatenation of other input streams, starting with an ordered set of input streams and reading from the first input stream, until the end of the file is reached, then reading from the second input stream, and so on, knowing that the end of the file that contains the last input stream is reached.
Sequenceinputstream can be used to combine multiple read streams into a single read stream.
Example:

 Public classSequencedemo { Public Static void Main(string[] args) {Sequenceinputstream sis =NULL; FileOutputStream fos =NULL;Try{Vector<fileinputstream> v =NewVector<fileinputstream> (); V.add (NewFileInputStream ("E:\\1.txt")); V.add (NewFileInputStream ("E:\\2.txt"));        Enumeration<fileinputstream> en = v.elements (); SIS =NewSequenceinputstream (en); FOS =NewFileOutputStream ("E:\\3.txt");byte[] buf =New byte[1024x768];intLen =0; while((Len=sis.read (BUF))!=-1) {Fos.write (buf,0, Len); }        }Catch(Exception e)        {E.printstacktrace (); }finally{Try{Fos.close (); }Catch(IOException e)            {E.printstacktrace (); }Try{Sis.close (); }Catch(IOException e)            {E.printstacktrace (); }        }    }}

Iii. ObjectInputStream and ObjectInputStream
ObjectOutputStream writes the basic data types and graphics of Java objects to OutputStream, you can use the InputStream read (refactor) object to implement persistent storage of objects by using files in the stream, if the stream is a network socket stream, You can refactor objects on another host and in another process.
Example:

publicvoidwriteObjthrow Exception{    new ObjectOutputStream(        new FileOutputStream("a.txt"));    oos.writeObject(new Person("lisi",24));oos.close();}

Iv. PipedInputStream and PipedOutputStream
Pipeline flow is an IO stream that involves multithreading. Pipeline flow because of the existence of pipelines, inputs and outputs can be directly connected by using a combination of threads.
Typically the data is read by a thread from the PipedInputStream object and written by other threads to the appropriate pipedoutputstream, which can cause a deadlock if only a single thread is used.
Example:

 Public  class Read implements Runnable{    PrivatePipedInputStream in; Read (PipedInputStream in) { This. in =; }@Override     Public void Run() {Try{byte[] buf =New byte[1024x768];intLen = In.read (BUF); String s =NewString (BUF,0, Len);        System.out.println (s);        In.close (); }Catch(IOException e)        {E.printstacktrace (); }    }} Public  class Write implements Runnable{    PrivateOutputStream out; Write (OutputStream out) { This. out = out; }@Override     Public void Run() {Try{Out.write ("AAAQQQ". GetBytes ());        Out.close (); }Catch(IOException e)        {E.printstacktrace (); }    }} Public  class pipeddemo {     Public Static void Main(string[] args) {PipedInputStream in =NewPipedInputStream (); PipedOutputStream out =NewPipedOutputStream ();Try{In.connect (out); }Catch(IOException e)        {E.printstacktrace (); } Read R =NewRead (in); Write W =NewWrite (out);NewThread (R). Start ();NewThread (W). Start (); }}

Wu, Randomaccessfile
Randomaccessfile is mainly used for random reading and writing of files, it inherits from the object class, and belongs to the tool class of self-faction. See random read-write file Randomaccessfile for specific usage.
Vi. DataOutputStream and DataInputStream
These two stream objects are primarily used to manipulate basic data types.
Example:

 Public void WriteData()Throwioexception{DataOutputStream dos =NewDataOutputStream (NewFileOutputStream ("Data.txt")); Dos.writeint (123); Dos.writeboolean (true); Dos.writedouble (999.99); Dos.writeutf ("Hello!" ");//utf-8 Modified versionDos.close ();} Public void ReadData()Throwioexception{DataInputStream dis =NewDataInputStream (NewFileInputStream ("Data.txt"));intNum=dis.readint ();Booleanb = Dis.readboolean ();DoubleD = dis.readdouble (); Dis.close ();}

The two Stream objects

Seven, Bytearrayinputstream, and Bytearrayoutputstream
are primarily used to manipulate byte arrays. The
Bytearrayinputstream contains an internal buffer that contains the bytes read from the stream. has an internal counter that tracks the next byte to be provided by the Read method. The methods in this class can still be called after the stream is closed, without IOException, that is, no need to close the stream object because the stream object does not invoke the underlying resource.
In addition, Bytearrayinputstream needs to receive a data source of the byte array type at the time of construction. The
Bytearrayoutputstream implements an output stream in which the data is written to a byte array, and the buffer grows automatically as the data is written continuously. You can use the Tobytearray () and ToString () methods to get the data. The methods in this class can still be called after the stream is closed, without generating ioexception.
In addition, Bytearrayoutputstream does not need to define the data purpose when it is constructed, because a variable-length byte array is already encapsulated inside the object, which is the data destination.
Example: Manipulating an array with the read and write thoughts of a stream.

public      Static  void  main  (string[] args) { Bytearrayinputstream bis = new  bytearrayinputstream ( "    ABCDEFG ". GetBytes ());    Bytearrayoutputstream BOS = new  bytearrayoutputstream ();    int  by=0 ; while  ((By=bis.read ())!=-1 )    {Bos.write (by); }system. out . println (Bos.size ()); System. out . println (Bos.tostring ()); Bos.write (new  FileOutputStream ( "a.txt" ));  

Viii. CharArrayReader and Chararraywriter
The stream object used to manipulate the character array, using the same bytearrayinputstream and Bytearrayoutputstream
Ix. StringReader and StringWriter
The stream object used to manipulate the string, using the same bytearrayinputstream and Bytearrayoutputstream

Dark Horse programmer-io Other stream objects in the package

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.