Java basics --- I/O technology (1), basics --- I

Source: Internet
Author: User

Java basics --- I/O technology (1), basics --- I

For any programming language, the input/output (I/O) system is complex and core. Related APIs are provided in the java. io. Package.

Concept division of java streaming

Stream direction:

    • Input stream: data source to program (inputStream, Reader read in)
    • Output stream: Write the program to the destination (OutPutStream, Writer)

Data Processing Unit:

    • Byte stream: reads data by byte (InputStream, OutputStream)
    • Bytes stream: reads data by character (Reader, Writer)

Different Functions

    • Node stream: read and write data directly from the data source or destination
    • Stream processing: processes the stream without directly connecting to the data source or destination. Child Workers process other streams to improve program performance.

The streams provided by Jdk inherit four categories: InputStream (byte input stream), OutputStream (byte output stream), Reader (character input stream), and Writer (character output stream ).

The following streams are commonly used in java I/O.

 

InputStream

Abstract class java. io. InputStream is the parent class of all byte input stream types. This class defines the basic methods for reading data in bytes, and has been divided and implemented in its subclass.

Three basic read methods:

  • Int read ()
  • Int read (byte [] buffer)
  • Int read (byte [] buffer, int offset, int length)

Other methods:

  • Void close ()
  • Int available ()
  • Skip (long n)
  • Boolean markSupported ()

InputStream class hierarchy

 

Import java. io. file; import java. io. inputStream; import java. io. fileInputStream; public class InputStreamDemo {public static void main (String args []) throws Exception {// thrown out of an Exception, do not process // Step 3. Use the File class to find a File f = new File ("d:" + File. separator + "test.txt"); // declare the File object // Step 1. instantiate the parent class Object InputStream input = null through subclass; // prepare an input object input = new FileInputStream (f); // instantiate the object through object polymorphism // Step 1 and perform the read operation byte B [] = New byte [1024]; // The array size is determined by the file int len = 0; int temp = 0; // receives each read data while (temp = input. read ())! =-1) {// indicates that there is still content. The file has not read step B [len] = (byte) temp; len ++;} // 4th. Close the output stream input. close (); // close the output stream \ System. out. println ("content:" + new String (B, 0, len); // convert the byte array to String output }};

 

 

OutputStream

Java. io. OutputStream corresponds to java. io. InputStream, which is the abstract parent class of all byte output stream types.

Three basic write methods:

  • Void write (int c)
  • Void write (byte [] buffer)
  • Void write (byte [] buffer, int offset, int length)

Other methods:

  • Void close ()
  • Void flush ()

OutputStream class hierarchy

Import java. io. file; import java. io. outputStream; import java. io. fileOutputStream; public class OutputStreamDemo {public static void main (String args []) throws Exception {// thrown out of an Exception, do not process // Step 3. Use the File class to find a File f = new File ("d:" + File. separator + "test.txt"); // declare the File object // Step 4. instantiate the parent class Object OutputStream out = null through subclass; // prepare an output object out = new FileOutputStream (f); // instantiate // Step 4: Write String str = "Hello World !!! "; // Prepare a string byte B [] = str. getBytes (); // only the byte array can be output, so the string is changed to the byte array out. write (B); // write data // step 3 close the output stream // out. close (); // close the output stream }};

 

Reader

The abstract class java. io. Reader is the parent class of all character input stream types. It declares methods used to read the character stream.

Three basic read methods:

  • Int read ()
  • Int read (char [] cbuf)
  • Int read (char [] cbuf, int offset, int length)

Other methods:

  • Void close ()
  • Boolean ready ()
  • Skip (long n)
  • Boolean markSupported ()
  • Void mark (int readAheadLimit)
  • Void reset ()

Reader class level

Import java. io. file; import java. io. reader; import java. io. fileReader; public class ReaderDemo {public static void main (String args []) throws Exception {// thrown out of an Exception, do not process // Step 3. Use the File class to find a File f = new File ("d:" + File. separator + "test.txt"); // declare the File object // Step 1. instantiate the parent class Object Reader input = null through subclass; // prepare an input object input = new FileReader (f); // Through object polymorphism, instantiate // Step 2 and read char c [] = new char [3rd]; // All Read all int temp = 0 in this array; // receives each int len = 0; // reads the content while (temp = input. read ())! =-1) {// if it is not-1, it indicates there is still content. You can continue to read c [len] = (char) temp; len ++ ;} // Step 3: Close the output stream input. close (); // close the output stream System. out. println ("content:" + new String (c, 0, len); // convert the character array to String output }};

 

 Writer

Java. io. Writer corresponds to the java. io. Reader class, which is the common parent class of all character output stream types.

Five Basic write methods:

  • Void write (int c)
  • Void write (char [] cbuf)
  • Void write (char [] cbuf, int offset, int leng)
  • Void write (String string)
  • Void write (String string, int offset, int length)

Other methods:

  • Void close ()
  • Void flush ()

Writer class level

Import java. io. file; import java. io. writer; import java. io. fileWriter; public class WriterDemo {public static void main (String args []) throws Exception {// thrown out of an Exception, do not process // Step 3. Use the File class to find a File f = new File ("d:" + File. separator + "test.txt"); // declare the File object // Step 4. instantiate the parent class Object Writer out = null through subclass; // prepare an output object out = new FileWriter (f); // instantiate the object through object polymorphism. // Step 4: Perform the write operation String str = "Hello World !!! "; // Prepare a string out. write (str); // output the content, save the file // step 3, and close the output stream out. flush (); // forcibly clear the content in the buffer. // out. close (); // at this time, it is not closed }};

Copy an instance:

Import java. io. *; public class Copy {public static void main (String args []) {if (args. length! = 2) {// check whether the two parameters System. out. println ("are incorrect. "); System. out. println ("Example: java Copy source file path destination file path"); System. exit (1); // system exit} File f1 = new File (args [0]); // File object of the source File: File f2 = new File (args [1]); // if (! F1.exists () {System. out. println ("the source file does not exist! "); System. exit (1);} InputStream input = null; // prepare the input stream object and read the source file OutputStream out = null; // prepare the output stream object, write the target file try {input = new FileInputStream (f1);} catch (FileNotFoundException e) {e. printStackTrace ();} try {out = new FileOutputStream (f2);} catch (FileNotFoundException e) {e. printStackTrace ();} if (input! = Null & out! = Null) {// determine whether the input or output is ready int temp = 0; try {while (temp = input. read ())! =-1) {// Start copying out. write (temp); // read and write} System. out. println ("Copy completed! ");} Catch (IOException e) {e. printStackTrace (); System. out. println (" Copy failed! ");} Try {input. close (); // close out. close (); // close} catch (IOException e) {e. printStackTrace ();}}}}

***In general, the input and output content requires byte or byte stream, but sometimes the byte stream needs to be changed to the byte stream form, or the byte stream needs to be changed to the byte stream form, so we need another set of conversion stream operation classes.

    • OutputStreamWriter: a subclass of Writer that converts the output bytes stream into a byte stream.
    • InputStreamReader: a sub-class of Reader that converts the input byte stream into a bytes stream.
Conversion steps:

If the file operation is used as an example, the total character data in the memory needs to be converted into a byte stream through OutputStreamWriter and stored in the file. During reading, the byte that is read must flow through InputStreamReader into a bytes stream.

For example, output a byte file output stream as a character

Import java. io. *; public class OutputStreamWriterDemo {public static void main (String args []) throws Exception {// All exceptions Throw File f = new File ("d:" + File. separator + "test.txt"); Writer out = null; // character output stream out = new OutputStreamWriter (new FileOutputStream (f); // The byte stream changes to bytes stream out. write ("hello world !! "); // Use the outputs stream to output out. close ();}};

You can also use the byte stream to read files from byte streams.

Import java. io. *; public class InputStreamReaderDemo01 {public static void main (String args []) throws Exception {File f = new File ("d:" + File. separator + "test.txt"); Reader reader = null; reader = new InputStreamReader (new FileInputStream (f )); // convert the byte stream to the bytes stream char c [] = new char [1024]; int len = reader. read (c); // read reader. close (); // close System. out. println (new String (c, 0, len ));}};

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.