J2SE knowledge point summary note (7) --- Java IO Part 3: Basic byte stream, j2se --- java

Source: Internet
Author: User

J2SE knowledge point summary note (7) --- Java IO Part 3: Basic byte stream, j2se --- java

J2SE knowledge point summary note (7) --- Java IO Part 3: Basic byte stream

-- Reprinted with the source: coder-pig


This section introduces:


In the previous section, we learned how to input data in the console and a preliminary understanding of the Java IO stream system diagram,

In this section, we will learn how to use basic byte streams and hidden streams ~ Start this section:




1. Methods for InputStream and OutputStream:

The first thing to note is that these two classes are abstract classes that implement various functions through subclasses;

The data unit is byte (1 byte = 8 bit). The following describes the related methods:


1) related methods of InputStream:

① Public abstract int read ():Read the data of a byte. The returned value is an int type value that is supplemented with 0 in the upper position;

If the returned value is-1, it indicates that no Bytes are read.

② Public int read (byte B []):Read data in bytes B. length and put it in array B. The returned value is the number of bytes read.
If the stream is located at the end of the file and no data is available,-1 is returned; equivalent to read (B, 0, B. length)

③ Public int read (byte B [], int off, int len ):Reads data of up to len bytes from the input stream and stores the data in the B array with the offset of off,

If the stream is located at the end of the file and no data is available,-1 is returned;

④ Public int available ():Returns the number of bytes that can be read from the input stream.

Ps: 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 that inherits the InputStream class.

⑤ Public int close ():Close the stream after use

⑥ Public long skip (long n ):N bytes in the input stream are ignored. The returned value is the number of bytes actually ignored. skip some bytes to read

7. public void mark (int readlimit ):Mark the current position in the input stream. If the reset method is called later, it will be located again at the last position.

This stream is used to re-read the same byte for later reading. The parameter readlimit indicates the number of bytes allowed to be read by marking invalid money.

Ps: jdk 1.6 does not seem to limit the number of bytes ~

Required public void reset ():Locate the stream again to the last mark method called!

Required public boolean markSupported ():Determines whether the input stream supports the mark and reset methods.


Ps: the mark and reset methods here, you may not understand very well. When learning BufferedInputStream,

I will give you an example. Then you will know the role of these two things...

Also, although read has three different constructor methods, we recommend that you use the following two methods. The first one is less useful !!!



2) related methods of OutputStream:

① Public void close ():Close this output stream and release all system resources related to this stream

② Public void flush ():Refresh the output stream and forcibly write all buffered output bytes.

③ Public abstract void write (int B ):Write the specified byte to this output stream.

Public void write (byte [] B ):Write B. length bytes from the specified byte array to this output stream

⑤ Public void write (byte [] B, int off, int len ):Write the len bytes starting from offset off in the specified byte array to this output stream.



Ps: in fact, these methods can be found by directly checking the documentation. I am also posting the analysis on the api ~

So it won't be used. If you haven't seen it, check the document first ~




2. Use of the FileInputStream and FileOutputStream classes:

Let's first introduce the first subclass of byte stream: ileInputStream and FileOutputStream!

It indicates reading and writing files in bytes;

Here we will not post relevant methods. Check the API documentation and go to the instance directly:


Code example: copying files

/** This method is used to copy files. It is the simplest and does not contain a buffer mechanism, so it is very junk ~ It is just for the reader to understand that * The parameter indicates the complete path of the copied file and the full path of the copied file **/public static void copyFile1 (String file1, String file2) throws IOException {File file = new File (file1); File outfile = new File (file2); FileInputStream inputStream = new FileInputStream (file); FileOutputStream outputStream = new FileOutputStream (outfile ); int I = 0; while (I! =-1) {I = inputStream. read (); outputStream. write (I) ;}// remember to close the stream inputStream. close (); outputStream. close ();}

Run:



Okay. If the above Code is copied to a large file, it will be okay. Wait for you to die... so we need to add the buffer,

To improve the speed of file copying, that isAdd a byte buffer ArrayOnly ~

The Code is also simple:

/** This method is based on 1 and adds the byte [] Array Buffer mechanism. When copying large files, its advantages are apparent ~ */Public static void copyFile2 (String file1, String file2) throws IOException {File file = new File (file1); File outfile = new File (file2 ); fileInputStream inputStream = new FileInputStream (file); FileOutputStream outputStream = new FileOutputStream (outfile); int I = 0; // set the buffer byte array to buffer 512 bytebyte [] buffer = new byte [512]; while (true) {if (inputStream. available () <512) {while (I! =-1) {I = inputStream. read (); outputStream. write (I);} break;} else {// when the file size is greater than 512 bytes, inputStream. read (buffer); outputStream. write (buffer) ;}// remember to close the stream inputStream. close (); outputStream. close ();}


Code parsing:

Is to add a character array of bytes, but the speed is significantly improved, do not believe it?

You can try to find a large file. For example, I use meitu xiuxiu, which is about 30 mb.

Method: It took about 1 minute to complete the replication, and it took a few seconds to copy it with a buffer ~




3) ByteArrayInputStream and ByteArrayOutputStream:

Known as byte stream: byte stream of the byte array. When an instance is created, a byte array buffer is created in the program,

There are a lot of usage during network transmission. Here we get the webpage source code for a page ~

ByteArrayOutputStream is widely used. In addition, toByteArray () is commonly used.

You can also expand it on your own. For example, the accessed url is an image and the image is saved locally ~


Code example:

/** Obtain the source code of a webpage: * The parameter is a link to a webpage: **/public static String getHtml (String path) throws Exception {URL url = new URL (path ); httpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setConnectTimeout (5000); conn. setRequestMethod ("GET"); if (conn. getResponseCode () = 200) {InputStream in = conn. getInputStream (); ByteArrayOutputStream out = new ByteArrayOutputStream (); byte [] buffer = new byte [1024]; I Nt len = 0; while (len = in. read (buffer ))! =-1) {out. write (buffer, 0, len);} in. close (); byte [] data = out. toByteArray (); String html = new String (data, "UTF-8"); return html;} return null ;}


Run:


Okay, so I can read the source code of a Web page ~





4) ObjectInputStream and ObjectOutputStream

The object byte stream can directly convert an object to a stream. In addition, the class corresponding to the converted object,

Serializable interface needs to be implementedIn addition, the transient and static member variables in the object will not be read or written.

Below is a simple code example:


Step 1: Define a service Bean:

import java.io.Serializable;public class Book implements Serializable {private String bName;private String bReporter;public Book(String bName, String bReporter) {super();this.bName = bName;this.bReporter = bReporter;}public String getbName() {return bName;}public void setbName(String bName) {this.bName = bName;}public String getbReporter() {return bReporter;}public void setbReporter(String bReporter) {this.bReporter = bReporter;}}


Step 2: first construct the low-level stream FileOutputStream and FileInputStream before using

ObjectOutputStream and ObjectInputStream:


Public static void main (String [] args) throws Exception {Book b1 = new Book ("how to get along with silly B", "pig "); book b2 = new Book ("funny self-cultivation", "Cat and kitten"); Book b3, b4; // note: to use advanced streams, you must first construct a low-level stream // ① write the object directly to the file FileOutputStream fout = new FileOutputStream ("D:/books.txt "); objectOutputStream out = new ObjectOutputStream (fout); out. writeObject (b1); out. writeObject (b2); // close the output stream out. close (); // ② read objects in the file: FileInputStream fin = new FileInputStream ("D:/books.txt"); ObjectInputStream in = new ObjectInputStream (fin); b3 = (Book) in. readObject (); b4 = (Book) in. readObject (); // close the input stream in. close (); System. out. println (b3.getbName () + "Author:" + b3.getbReporter (); System. out. println (b4.getbName () + "Author:" + b4.getbReporter ());}


Run:



At the same time, we can see the book.txt file under the D Drive, but it is garbled after opening,

This is because we write byte streams ~ Garbled characters appear in Chinese. If you want to solve this problem,

You can use the FileWriter and FileReader mentioned later ~






5) PipedOutputStream and PipedInputStream

This is a pipeline stream, which is a little more complicated than the previous several streams,

Through thisThe two streams allow multi-thread communication between threads through pipelines. They need to be used together!

Different from the pipelines in Linux and Unix systems, they are two processes with different address spaces that can communicate through pipelines,

WhileIn Java, different threads run in the same process!

Principle: PipedInputStream hasBuffer, Use the InputStream method to read the bytes in its Buffer;

The bytes in the Buffer are put by the PipedOutputStream method that calls PipedInputStream;

In addition, it is not recommended to write the objects corresponding to the two streams in the same thread, otherwise it will easily lead to deadlocks,

You can use the connect () method to set up this pipeline and then transmit data ~


Here is a simple example for you to understand ~


1) SendThread. java: (output stream)

Import java. io. IOException; import java. io. pipedOutputStream; public class SendThread extends Thread {private PipedOutputStream out = new PipedOutputStream (); public PipedOutputStream getOutputStream () {return out;} public void run () {String strInfo = "I am something written by PipedOutputStream"; try {out. write (strInfo. getBytes (); out. close ();} catch (IOException e) {e. printStackTrace ();}}}

2) ReceiverThread. java: (input stream)


import java.io.IOException;import java.io.PipedInputStream;public class ReceiverThread extends Thread {private PipedInputStream in = new PipedInputStream();public PipedInputStream getInputStream() {return in;}public void run() {byte[] buf = new byte[1024];try {int len = in.read(buf);System.out.println(new String(buf, 0, len));in.close();} catch (IOException e) {e.printStackTrace();}}}


Test class: Test5.java:

Import java. io. IOException; import java. io. pipedInputStream; import java. io. pipedOutputStream; public class Test5 {public static void main (String [] args) {ReceiverThread rThread = new ReceiverThread (); SendThread sThread = new SendThread (); // obtain the corresponding stream: pipedOutputStream out = sThread. getOutputStream (); PipedInputStream in = rThread. getInputStream (); try {// pipeline link out. connect (in); sThread. start (); rThread. start ();} catch (IOException e) {e. printStackTrace ();}}}


Run:





6) SequenceInputStream merge stream:

If you want to read data from multiple input streams to the program, you can use the merged stream,

SequenceInputStream combines the connected stream set into an input stream and reads it from the first input stream,

Until the end of the file is reached, read from the second input stream, and so on until the end of the file containing the last input stream is reached;

The function of merging streams is to combine multiple sources into one source!


Note: (constructor)

SequenceInputStream provides two different constructor methods:

1 ~ SequenceInputStream (Enumeration <? Extends InputStream> e)

2 ~ SequenceInputStream (InputStream s1, InputStream s2)


PS: This Enumertaion is an interface. The Enumeration interface defines a means to get continuous data from a data structure.

This interface provides two methods:

Boolean hasMoreElements (): test whether this enumeration contains more elements.

NextElement (): If this enumeration object has at least one available element, the next element of this enumeration is returned.

Enumertaion is not detailed here. For more information, see this document ~




Next we will write two simple mini programs for our understanding:

① Use two streams as the parameter constructor:

public static void main(String[] args) throws IOException {          InputStream s1 = new ByteArrayInputStream("ABC".getBytes());          InputStream s2 = new ByteArrayInputStream("abc".getBytes());          InputStream in = new SequenceInputStream(s1, s2);          int data;          while ((data = in.read()) != -1) {              System.out.println(data);          }          in.close();      }  

Running result: (corresponding to the ASCII code value of ABCabc. Don't ask why I don't need Chinese characters, because this section describes the byte stream, one Chinese Character and two bytes ~)




② The constructor using Enumeration as the parameter:

Public static void main (String [] args) throws IOException {// create the merged stream SequenceInputStream sin = null; // create the output stream BufferedOutputStream bout = null; try {// construct the stream set Vector <InputStream> vector = new Vector <InputStream> (); vector. addElement (new FileInputStream ("D :\\ test1.txt"); vector. addElement (new FileInputStream ("D :\\ test2.txt"); vector. addElement (new FileInputStream ("D: \ test3.txt"); vector. addElement (New FileInputStream ("D: \ test4.txt"); Enumeration <InputStream> e = vector. elements (); sin = new SequenceInputStream (e); bout = new BufferedOutputStream (new FileOutputStream ("D: \ textUnion.txt ")); // read/write Data byte [] buf = new byte [1024]; int len = 0; while (len = sin. read (buf ))! =-1) {bout. write (buf, 0, len); bout. flush () ;}} catch (FileNotFoundException e1) {e1.printStackTrace ();} catch (IOException e1) {e1.printStackTrace ();} finally {try {if (sin! = Null) sin. close ();} catch (IOException e) {e. printStackTrace ();} try {if (bout! = Null) bout. close () ;}catch (IOException e) {e. printStackTrace ();}}}

Then we create the following txt files in the Directory D: test1, test2, test3, and test4:

Tease A, tease B, tease C, tease D

Run:

The testunion.txt file will be produced under the D Drive. After opening the file, you can see:









The last two sentences are as follows:

Okay, let's talk about the basic byte stream in Java I/O. Now let's review the following topics in this section:

① Methods related to the InputStream and OutputStream parent classes

② Use of FileInputStream and FileOutputStream file read/write classes, adding a buffer array to improve read/write efficiency ~

③ ByteArrayInputStream and ByteArrayOutputStream byte array classes. We wrote an example of getting the webpage source code:

④ ObjectInputStream and ObjectOutputStream can be used to read and write objects.

Conversion from object to stream to object. Note that the class to which this object belongs must inherit the Serializable interface!

⑤ PipedOutputStream and PipedInputStream pipe input and output class, which are used for communication between threads,

Generally, avoid writing the two to the same thread, otherwise it will easily lead to deadlocks. This section only provides a simple application example.

Further research is required ~

6 SequenceInputStream: Merge multiple input streams into one input stream. There are two constructor forms:

Two input streams or one Enumeration parameter are used. You can refer to the following example ~



So here is the basic byte stream for this section. Thank you for reading ~

If you think this article is okay, you can give a thumbs up in 1 s so that more friends can see this article ~ Thank you very much ~





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.