0. Overview:
Stream-based I/O in Java is built on 4 abstract classes, 2 of which are byte streams, and 2 are character streams.
BYTE stream:
Inputstream/outputstream
When manipulating bytes or other binary objects, you should use a byte stream.
Character Stream:
Reader/writer
When manipulating characters or strings, you should use a character stream.
1. InputStream
InputStream: Input byte stream, which is an abstract class.
Common Main methods:
int read ()
Returns an integer representing the next available byte, which returns 1 when the file reaches the end.
int read (Bute buffer[])
An attempt was made to read Buffer.length bytes into buffer, returning the number of bytes actually successfully read; The file returns-1 at the end.
int read (bute buffer[], int offset, int numbytes)
Attempts to read numbytes bytes into buffer, starting from buffer[offset] to save the read bytes;
Returns the number of bytes actually read successfully; The file returns to the end-1.
2. OutputStream
OutputStream: Output byte stream, which is an abstract class.
Common Main methods:
void write (int b)
Writes a single byte to the output stream.
void write (byte buffer[])
Writes a complete array of bytes to the output stream.
void write (byte buffer[], int offset, int numbytes)
NumBytes bytes are written to the output stream starting from Buffer[offset].
void Flush ()
Ends the output state and refreshes the output buffer.
3. FileInputStream
The file reads the byte stream.
Common constructors:
FileInputStream (String FilePath) (more commonly used)
FileInputStream (File fileobj)
An example of a homogeneous input stream to read the contents of a file, demonstrating 3 ways (single-byte reading, byte-array reading, ignoring partial-byte reads)
The code is as follows:
PackageCorejava8.io.stream;ImportJava.io.*; Public classFileinputstreamdemo { Public Static voidMain (String args[]) {intsize; //Use try-with-resources to close the stream Try(FileInputStream f =NewFileInputStream ("Src/corejava8/io/stream/fileinputstreamdemo.java") {System.out.println ("Total Available Bytes:" + (size =f.available ())); intn = size/40; //each single-byte read by loopSystem.out.println ("First" + N + "bytes of the file one read () at a time"); for(inti = 0; I < n; i++) {System.out.print (Char) F.read ()); } System.out.println ("\nstill Available:" +f.available ()); System.out.println ("--------------------------------------------------------------"); //byte array ReadSystem.out.println ("Reading the next" + N + "with one read (b[])"); byteB[] =New byte[n]; if(F.read (b)! =N) {System.err.println ("Couldn ' t read" + N + "bytes."); } System.out.println (NewString (b, 0, N)); System.out.println ("\nstill Available:" + (size =f.available ())); System.out.println ("--------------------------------------------------------------"); //ignore partial byte readsSystem.out.println ("Skipping half of remaining bytes with skip ()"); F.skip (Size/2); System.out.println ("Still Available:" +f.available ()); System.out.println ("Reading" + N/2 + "into the end of array"); if(F.read (b, N/2, N/2)! = N/2) {System.err.println ("Couldn ' t read" + N/2 + "bytes."); } System.out.println (NewString (b, 0, b.length)); System.out.println ("\nstill Available:" +f.available ()); } Catch(IOException e) {System.out.println ("I/O Error:" +e); } }}
The results of the operation are as follows:
Total Available bytes:1704
First bytes of the file one read () at a time
Package corejava8.io.stream;
Import java.
Still available:1662
--------------------------------------------------------------
Reading the next with one read (b[])
io.*;
public class Fileinputstreamdemo {
Still available:1620
--------------------------------------------------------------
Skipping half of remaining bytes with Skip ()
Still available:810
Reading into the end of array
io.*;
public class Fm.err.println ("couldn
Still available:789
4. FileOutputStream
The file output byte stream used to write bytes to the file.
4 Common constructors:
FileOutputStream (String FilePath)
FileOutputStream (File fileobj)
FileOutputStream (String FilePath, Boolean append)
FileOutputStream (File fileobj, Boolean append)
Before we start with the following example, let's first mention a detail of the flow closure, which is
Legacy code prior to JDK 7 uses an explicit call to the close () method to close the stream, an approach
Rather clumsy.
The Old code:
Try{fileoutputstream F0=NewFileOutputStream ("File1.txt"); //File Write operations}Catch(IOException e) {System.out.println ("An I/O Error occurred"); } finally { Try { if(F0! =NULL) F0.close (); } Catch(IOException e) {System.out.println ("Error Closing file1.txt"); } }}
New Code (JDK 7 and later code):
Try New FileOutputStream ("file1.txt")) { // file write operation catch(IOException E { System.out.println ("An I/O Error occurred");}
Does the code become more concise?
Our examples are:
PackageCorejava8.io.stream;ImportJava.io.*; Public classFileoutputstreamdemo { Public Static voidMain (String args[]) {string source= "Now was the time for all good men\n" + "to come to the aid of their country\n" + "and pay their due Es. "; byteBuf[] =source.getbytes (); //Use try-with-resources to close the files. Try(FileOutputStream F0 =NewFileOutputStream ("File1.txt"); FileOutputStream F1=NewFileOutputStream ("File2.txt"); FileOutputStream F2=NewFileOutputStream ("File3.txt")) { //write to first file for(inti = 0; i < buf.length; i++) F0.write (Buf[i]); //write to second fileF1.write (BUF); //write to third fileF2.write (BUF, 3, buf.length-3); } Catch(IOException e) {System.out.println ("An I/O Error occurred"); } }}
The results of the operation are as follows:
First, the second file content is:
Now was the time for all good Men
To come to the aid of their country
and pay their due taxes.
The third file skips the first word and reads:
is the good
To come to the aid of their country
and pay their due taxes.
In the code above:
byte buf[] = Source.getbytes ();
An array of bytes used to get the source data (string).
Core Java-Stream (stream)-byte stream and character stream (one)