Home  >  Article  >  Java  >  Java input stream output stream

Java input stream output stream

大家讲道理
大家讲道理Original
2017-05-28 11:28:071558browse


1. What is IO

I/O operations in Java mainly refer to using Java for input and output operations. All I/O mechanisms in Java are based on Data streams perform input and output. These data streams represent a flowing sequence of characters or bytes. Java's I/O streams provide standard methods for reading and writing data. Any object representing a data source in Java will provide methods for reading and writing its data in a data stream.​

​ Java.io is the main software package for most data flow-oriented input/output classes. In addition, Java also provides support for block transmission, and block IO is used in the core library java.nio.

The advantage of stream IO is that it is simple and easy to use, but the disadvantage is that it is less efficient. Block IO is very efficient, but programming is more complicated.
Java IOModel :
Java’s IO model design is very excellent. It uses the Decorator mode to divide Streams by function. You can dynamically assemble these Streams to get your required functionality. For example, if you need a buffered file input stream, you should use a combination of FileInputStream and BufferedInputStream.



##2.

Basic concepts of data flow

Data flow is a collection of continuous data, just like the water flow in a water pipe, water is supplied bit by bit at one end of the water pipe, and at the other end of the water pipe What you see at the other end is a continuous stream of water. The data writing program can write data into the data flow pipeline segment by segment. These data segments will form a long data stream in sequence. For data reading programs, the segmentation of the data stream during writing cannot be seen. Data of any length can be read each time, but only the previous data can be read first, and then the subsequent data can be read. data. Regardless of whether the data is written in multiple batches or written as a whole at once, the effect when reading is exactly the same.

"A stream is the source or end point of data stored in a disk or

other peripheral device."

There are three ways to store data on a computer, one is External storage, one is memory, and the other is

cache. For example, the hard disk, magnetic disk, USB flash drive, etc. on the computer are all external storage. There is a memory stick on the computer, and the cache is in the CPU. External storage has the largest storage capacity, followed by memory, and finally cache. However, the reading of data from external storage is the slowest, followed by memory, and cache is the fastest. Here is a summary of reading data from external memory to memory and writing data from memory to external memory. For the understanding of memory and external storage, we can simply understand it as a container, that is, external storage is a container, and memory is another container. So how do you read the data in the external storage container into the memory container and how do you store the data in the memory container into external storage?

In the Java

class library, the content of the IO part is very large, because it covers a wide range of fields:

Standard input and output , file operations, data flows on the network,

string streams, object streams, zip file streams, etc., The input and output abstraction in java is called a stream, like a water pipe, connects two containers. Reading data from external memory into memory is called an input stream, and writing data from memory into external memory is called an output stream.

Stream is a very vivid concept. When the program needs to read data, it will open a stream to the data source. This data source can be a file, memory, or network connection. Similarly, when the program needs to write data, it will open a stream to the destination.


The basic concepts summarized are as follows:

1) Data flow:

A set of ordered, Data sequence of starting and ending bytes. Including input stream and output stream.

2) Input Stream(Input Stream):

The program reads the data source from the input stream. Data sources include the outside world (keyboard, files, network...), which is the communication channel that reads the data source into the program

3) Output stream :

The program writes data to the output stream. A communication channel that outputs data in the program to the outside world (monitor, printer, file, network...).

The purpose of using data flow is to make the output and input independent of the device.

Input Stream does not care what device the data source comes from (keyboard, file, network)
Output Stream does not care what device the data is intended for (keyboard, file, network)

4 Data stream classification:

The data in the stream sequence can be either unprocessed original binary data, or specific data that conforms to a certain format after certain encoding. Therefore, streams in Java are divided into two types:
1) Byte stream: The smallest data unit in the data stream is bytes
2) Character stream: data The smallest data unit in the stream is a character. Characters in Java are Unicode encoded, and one character occupies two bytes.



##3. Standard I/O

Java programs can exchange brief information with the outside world through command line parameters. At the same time, it also stipulates information exchange with standard input and output devices, such as keyboards and monitors. The way. Through files, information in any data form can be exchanged with the outside world.

1. Command line parameters


  1. ##public

    class TestArgs {

  2. public

    static void main(String[ ] args) {

  3. ##for

    (int i = 0; i < args.length; i++) { ## System.out.

    print
  4. ln(
  5. "args[" + i +

    "] is <" + args[i] + ">");

  6. # }  
  7. }  
  8. ## Run command: Java Java C VB

Run result:

args[0] is

args[1] is

args[2] is

2. Standard input, output data stream

The standard data stream that comes with the java system: java.

lang

.System:

java.lang.System


    public
  1. final

  2. class System
  3. extends Object{ ##static PrintStream err;//Standard error stream (output)

  4. static InputStream in;//Standard input (keyboard input stream)

  5. ##static PrintStream out;//Standard output Stream (monitor output stream)

  6. }

  7. ##

    Note:
    (1) The System class cannot create objects , and can only use its three static members directly.
    (2) Whenever the main method is executed, the above three objects are automatically generated.

    1) Standard output stream System.out

    System.out outputs data to the standard output device, its data type is PrintStream. Method:

    Void print(parameter)

    Void println(parameter)

    2) Standard input stream System.in

    System.in reads standard input device data (obtains data from standard input, usually the keyboard), and its data type is InputStream. Method:

    int read() //Return the ASCII code. If the return value = -1, it means that no bytes have been read and the reading work has ended.

    int read(byte[] b)//Read multiple bytes into buffer b. The return value is the number of bytes read.

    For example:



    1. ##import java.io.*;

    2. public class StandardInputOutput {

    3. ##public

      static void main(String args[]) {

    4.                                                                                                
    5. System.out.println ( "Please input:");

      ser ((b = System.in.read()) != -
    6. 1) {
    7. ## System.out.print((
    8. char ) b);
    9. # System.out.println(e.toString());

    10. } }  

    11. }  
    12. Waiting for keyboard input, whatever the keyboard inputs, it will print out:

    13. 3) Standard error stream

    14. System.err outputs standard error

      , its data type is PrintStream. Please refer to

      API
    15. for detailed instructions.
    16. Standard output calls the println method through System.out to output parameters and wrap the parameters, while the print method outputs the parameters but does not wrap the line. The println or print method implements multiple methods of outputting basic data types through
    17. overloading

      , including output parameter types of boolean, char, int, long,

      float
    18. and double. At the same time, methods whose output parameter types are char[], String and Object are also overloaded. Among them, the print(Object) and println(Object) methods will call the toString method of the parameter Object at runtime.


    ##import java.io.BufferedReader;

    import java.io.IOException;

    ##import java.io.InputStreamReader;

    public class StandardInputOutput {


    ##public
      static
    1. void main(String args[]) {

    2. String s;

    3. //Create a buffer reader to read data line by line from the keyboard

    4. InputStreamReader ir = new InputStreamReader(System.in);

    5. # BufferedReader in =

      new BufferedReader( ir);

    6. ## System.out.println(
    7. "Unix system: ctrl-d or ctrl-c

      Exit"

    8.                                                                                                                                                                      
    9.                                                                                                                                                                                                                                                                  . ##();

    10.              // If an I/O error occurs when the readLine() method is running, an IOException will be thrown

    11. WHILE (s! =

      NULL
    12. ) {
    13. ## System.out.println (
    14. "Read: " + s);
    15. ## s = in.readLine();

    16. }                                                                                                                                                                                                                                  

    17. ## }
    18. catch (IOException e) {

      // Catch any IO exceptions.

    19. ## e.printStackTrace();

    20. }  

    21. ##   }  
    22. }  

    23. ##4.java.IO Hierarchy Architecture
    24. The most important things in the entire Java.io package are 5 classes and an

      interface
    25. . The five classes refer to File, OutputStream, InputStream, Writer, and Reader; one interface refers to Serializable. If you master these core operations of IO, you will have a preliminary understanding of the IO system in Java
    26. Java I/O mainly includes the following levels, including three parts:
    1. Streaming part

    --IO The main part;

    2. Non-streaming part

    --mainly includes some classes that assist the streaming part, such as: File class, RandomAccessFile class and FileDescriptor class;

    3. Other classes
    --Classes related to

    security

    in the file reading part, such as: SerializablePermission class, and

    file system## related to the local operating system #Classes, such as: FileSystem class, Win32FileSystem class and WinNTFileSystem class.


    The main categories are as follows:

    1. File (file characteristics and management): used for description information of files or directories, such as generating new directories, modifying file names,

    delete

    File, determine the path of the file, etc.

    2. InputStream (binary format operation): Abstract class, byte-based input operation, is the parent class of all input streams. Defines common characteristics that all input streams have.

    3. OutputStream (binary format operation): abstract class. Byte-based output operations. Is the parent class of all output streams. Defines common characteristics that all output streams have.

    Characters in Java adopt the Unicode standard. One character is 16 bits, that is, one character is represented by two bytes. To this end, streams for processing characters were introduced in JAVA.

    4. Reader (file format operation): abstract class, character-based input operation.

    5. Writer (file format operation): abstract class, character-based output operation.

    6. RandomAccessFile (random file operation): It has rich functions and can perform access (input and output) operations from any location in the file.

    The architecture of IO stream in Java is as shown in the figure:





    ##5. Not Streaming file class--File class

    In the java.io package of the Java language, the File class provides operations and management methods for describing files and directories. However, the File class is not a subclass of InputStream, OutputStream, or Reader or Writer, because it is not responsible for data input and output, but is specifically used to manage disk files and directories.

    Function: The File class is mainly used to name files,

    queryfilepropertiesandprocess filesdirectories.


    1. #public  

      class   File   extends Object  

    2. implements Serializable,Comparable

    3. {}


    The File class provides a total of three different

    constructors

    , which can flexibly receive file and directory name information in different parameter forms. Constructor: 1) File (String pathname)
    Example: File f1=new File("FileTest1.txt"); //Create file object f1, pointed by f1 The file is created in the current directory FileTest1.txt

    2) File (String parent , String child)
    Example: File f2=new File(“D:\\

    dir

    1","FileTest2.txt") ;// Note: The D:\\dir1 directory must exist in advance, otherwise an exception will occur 3) File (File parent , String child)
    Example: File f4=new File("\\dir3"); File f5=new File(f4,"FileTest5.txt"); //If the \\dir3 directory does not exist, use f4 .mkdir() first creates

    Once a File object corresponding to a disk file or directory is created, you can obtain the attributes of the file or directory by calling its method.

    1) public boolean exists( ) to determine whether the file or directory exists

    2) public boolean isFile( ) to determine whether it is a file or directory

    3) public boolean isDirectory( ) to determine whether it is a file or directory
      4) public String getName( ) returns the file name or directory name
      5) public String getPath( ) returns the path of the file or directory.
    6) public long length( ) Get the length of the file
    7) public String[ ] list ( ) Save all the file names in the directory in a string
    array
    and return it. The File class also defines some methods for managing and operating files or directories. Commonly used methods are:

    1) public boolean renameTo(File newFile); Rename a file

    2) public void
    delete
    ( ); Delete file 3) public boolean mkdir( ); Create directory


    Example:



    1. #import java.io.File;

    2. import java.io.IOException;

    3. ##public

      class TestFile {

    4. public

      static void main(String args[]) throws IOException {

    5. File dir =
    6. new File(

      "\\root");

      ## File f1 =
    7. new File(dir,
    8. "fileOne.txt");

      ## File f2 =

      new File(dir,
    9. "fileTwo.java");
    10. ##// After the file object is created, the specified file or directory may not physically exist

    11.                                                                                                                                                                                                                        

    12. ##                                                                                                                                                                                                                                      
    13.                                                                                                                                              # System.out.println("f1's AbsolutePath= " + f1.getAbsolutePath());

      ## System.out.println(
    14. "f1 Canread =" + f1.canRead());
    15. System.out.println(

      "f1's len= " + f1.length());

    16. String[] FL;

    17. int count =

      0;
    18. ##     FL = dir.list(); i < FL.length; i++) {
    19. (FL[i] +
    20. "is in \\root");

      ## }
    21. ## System.out. println("there are" + count + "file in //root");

    22. ## }
    23. }

    24. illustrate: Methods of the File class: (1) exists() tests whether the specified file or directory exists on the disk (2) mkdir() creates the directory specified by the file object (single-layer directory) (3) createNewFile() creates the file specified by the file object(4) list() returns all file name strings in the directory

    25. 6. Java.IO stream class library

    26. 1. Four basic classes of io stream
    27. The java.io package contains streaming I/O All classes required. There are four basic classes in the java.io package: InputStream, OutputStream and Reader and Writer classes, which handle byte streams and character streams respectively:

    28. Basic data stream I/O


      Input/Output

      Byte stream

      Character stream

      Input stream

      Inputstream

      Reader

      OutputStream

      OutputStream

      Writer


      A variety of other streams in Java are derived from them:

      ## JDK1.4 version has introduced a new I/O class library, which is located in java In the .nio package, the new I/O class library uses channels and buffers to improve the efficiency of I/O operations.

      In the java.io package, java.io.InputStream represents the byte input stream, and java.io.OutputStream represents the byte output stream, which is at the top level of the java.io package. Both classes are abstract classes, which means that they cannot be instantiated and must be subclassed to achieve certain functions.

      1. Specific classification of io streams

      1. Overall classification by I/O type:

       

      1. Memory 1) Read and write data from/to the memory array: CharArrayReader, CharArrayWriter, ByteArrayInputStream, ByteArrayOutputStream             2) From/to the memory string Read and write data StringReader, StringWriter, StringBufferInputStream

      2.Pipe pipeline Realize the input and output of the pipeline (inter-process communication): PipedReader, PipedWriter, PipedInputStream, PipedOutputStream
      3.File file flow. Read and write files: FileReader, FileWriter, FileInputStream, FileOutputStream
      4. ObjectSerialization object input and output: ObjectInputStream, ObjectOutputStream
      5.DataConversion data stream Press Basic data type reading and writing (the data processed are Java’s basic types (such as Boolean, byte, integer and floating point number)): DataInputStream, DataOutputStream
      6.Printing Contains convenient printing methods: PrintWriter, PrintStream
      7.Buffering buffering Cache data when reading or writing out to reduce the number of I/O: BufferedReader, BufferedWriter, BufferedInputStream, BufferedOutputStream
      8.Filtering Filtering stream, filtering when data is read or written: FilterReader, FilterWriter, FilterInputStream, FilterOutputStream through
      9.Concatenation merge Input Connect multiple input streams into one input stream: SequenceInputStream
      10.Counting Counting Count lines when reading data: LineNumberReader, LineNumberInputStream
      11. Peeking Ahead Pre-read through the caching mechanism: PushbackReader, PushbackInputStream
      12.Converting between Bytes and Characters Convert the byte stream into a character stream according to certain encoding/decoding standards, or perform Reverse conversion (Stream to Reader, Writer conversion class): InputStreamReader, OutputStreamWriter

      2. Classification by data source (destination): 1. File (file): FileInputStream , FileOutputStream, FileReader, FileWriter
      2. byte[]: ByteArrayInputStream, ByteArrayOutputStream
      3. Char[]: CharArrayReader, CharArrayWriter
      4. String: StringBufferInputStream, StringReader, StringWriter
      5. Network data flow :InputStream, OutputStream, Reader, Writer



      ##7. Byte stream InputStream /OutputStream

      1. InputStream

      Abstract class InputStream is a byte input stream. It itself is an abstract class and must rely on its subclasses. Implementing various functionality, this abstract class is the superclass of all classes that represent byte input streams.

      Inherited

      The streams from InputStream are used to input data into the program, and the data unit is bytes (8bit);

      InputStream is a class for inputting byte data, so the InputStream class provides three overloaded read methods. Common methods in the Inputstream class:
      (1) public abstract int read(): Read a byte The data, the return value is an int type value with the high bits filled with 0. If the return value = -1, it means that no bytes have been read and the reading work has ended.
       (2) public int read(byte b[ ]): Read b.length bytes of data and put it into the b array. The return value is the number of bytes read. This method is actually implemented by calling the next method
      (3) public int read(byte b[ ], int off, int len): Read up to len bytes of data from the input stream and store it in the offset into the b array whose shift amount is off.
       (4) public int available(): Returns the number of bytes that can be read in 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 that inherits the InputStream class to be useful.
       (5) public long skip(long n): Ignore n bytes in the input stream, the return value is the number of bytes actually ignored, skip some bytes to read
       (6) public int close(): We finish using Finally, the stream we opened must be closed.

      Main subclasses:

      1) FileInputStream uses a file as an InputStream to implement the file Read operation
      2) ByteArrayInputStream: Use a buffer in memory as an InputStream
      3) StringBufferInputStream: Use a String object as an InputStream
      4) PipedInputStream: Implement the concept of pipe, mainly in threads Use
      5) SequenceInputStream: Merge multiple InputStreams into one InputStream

      2. OutputStreamAbstract class

      OutputStream provides three write methods for data output, which corresponds to InputStream.
       1. public void write(byte b[ ]): Write the byte in parameter b to the output stream.
       2. public void write(byte b[ ], int off, int len): Write len bytes of parameter b starting from offset off to the output stream.
       3. public abstract void write(int b): First convert int to byte type, and write the low byte to the output stream.
       4. public void
      flush( ): Output all the data in the data buffer and clear the buffer.
       5. public void close(): Close the output stream and release the system resources related to the stream.

      Main subclasses:

      1) ByteArrayOutputStream: Store information in a buffer in memory
      2) FileOutputStream: Store information Store in the file
      3) PipedOutputStream: implements the concept of pipe, mainly used in threads
      4) SequenceOutputStream: merges multiple OutStreams into one OutStream

      Determination of the end of the stream: method read When the return value of () is -1; when the return value of readLine() is null.

      3. File input stream: FileInputStream class

      FileInputStream can use the read() method to read in one byte at a time and return it as int type, or use the read() method to read in To a byte array, how many bytes are read as there are elements in the byte array. In the process of reading or writing the entire file, such a byte array is usually used as a buffer, because such a byte array usually plays an intermediate role in receiving data.

      Function: Use the file as The data flow for the data input source. In other words, it is a class that opens a file and reads data from the file into memory.
      Usage method (1)
      File fin=new File("d:/abc.txt");
      FileInputStream in=new FileInputStream( fin);

      Usage method (2)
      FileInputStream in=new FileInputStream(“d: /abc.txt”);

      Program example:
      Display the contents of the InputFromFile.java program on the monitor


      1. #import java.io.IOException;

      2. import java.io.FileInputStream;  

      3. ;  

      4. public class TestFile {  

      5.     public static void main(String args[]) throws IOException {  

      6.         try{      

      7.                FileInputStream rf=new   FileInputStream("InputFromFile.java");  

      8.                int n=512;   byte  buffer[]=new  byte[n];     

      9.                while((rf.read(buffer,0,n)!=-1)&&(n>0)){  

    29.                    System.out.println(new String(buffer) );  

    30.                 }  

    31.                 System.out.println();  

    32.                 rf.close();  

    33.         } catch(IOException  IOe){        

    34.               System.out.println(IOe.toString());  

    35.         }  


    36.     }  


    37. }  


     

    4.文件输出流:FileOutputStream类

       作用:用来处理以文件作为数据输出目的数据流;或者说是从内存区读数据入文件

     

          FileOutputStream类用来处理以文件作为数据输出目的数据流;一个表示文件名的字符串,也可以是File或FileDescriptor对象。 
      创建一个文件流对象有两种方法: 
      方式1: 
       File   f=new  File (“d:/myjava/write.txt ");
            FileOutputStream  out= new FileOutputStream (f);
      方式2: 
      FileOutputStream out=new FileOutputStream(“d:/myjava/write.txt "); 
      方式3:构造函数将 FileDescriptor()对象作为其参数。 
      FileDescriptor() fd=new FileDescriptor(); 
      FileOutputStream f2=new FileOutputStream(fd); 
      方式4:构造函数将文件名作为其第一参数,将布尔值作为第二参数。 
      FileOutputStream f=new FileOutputStream("d:/abc.txt",true); 
      注意: (1)文件中写数据时,若文件已经存在,则覆盖存在的文件;(2)的读/写操作结束时,应调用close方法关闭流。 

     


    程序举例:使用键盘输入一段文章,将文章保存在文件write.txt中



    1. import java.io.IOException;  

    2. import java.io.FileOutputStream;  

    3. public class TestFile {  

    4.     public static void main(String args[]) throws IOException {  

    5.         try {  

    6.             System.out.println("please Input from      Keyboard");  

    7.             int count, n = 512;  

    8.             byte buffer[] = new byte[n];  

    9.             count = System.in.read(buffer);  

    10.             FileOutputStream wf = new FileOutputStream("d:/myjava/write.txt");  

    11.             wf.write(buffer, 0, count);  

    12.             wf.close(); // 当流写操作结束时,调用close方法关闭流。  

    13.             System.out.println("Save to the write.txt");  

    14.         } catch (IOException IOe) {  

    15.             System.out.println("File Write Error!");  

    16.         }  

    17.     }  


    18. }  


    5. FileInputStream流和FileOutputStream的应用

    利用程序将文件file1.txt 拷贝到file2.txt中。


    1. import java.io.File;  

    2. import java.io.IOException;  

    3. import java.io.FileOutputStream;  

    4. import java.io.FileInputStream;  


    5. public class TestFile {  

    6.     public static void main(String args[]) throws IOException {  

    7.         try {  

    8.             File inFile = new File("copy.java");  

    9.             File outFile = new File("copy2.java");  

    10.             FileInputStream finS = new FileInputStream(inFile);  

    11.             FileOutputStream foutS = new FileOutputStream(outFile);  

    12.             int c;  

    13.             while ((c = finS.read()) != -1) {  

    14.                 foutS.write(c);  

    15.             }  

    16.             finS.close();  

    17.                           foutS.close(); ##         System.err.println(

      "FileStreamsTest: " + e);
    18. }

    19. ##6. Buffered InputStream/ BufferedOutputStream


    # It is very time-consuming for the computer to access external devices. The higher the frequency of accessing external memory, the greater the probability that the CPU will be idle. In order to reduce the number of accesses to external memory, more data should be read and written in one access to the peripheral. To this end, in addition to the reading and writing mechanisms necessary for exchanging data between programs and flow nodes, a buffering mechanism should also be added. Buffered stream means that each data stream is allocated a buffer, and a buffer is a memory that temporarily stores data. This can reduce the number of hard disk accesses and improve transmission efficiency.


    BufferedInputStream: When writing data to the buffered stream, the data is first written to the buffer. After the buffer is full, the system sends the data to the output device in one go.

    BufferedOutputStream: When reading data from the buffered stream, the system first reads the data from the buffer. When the buffer is empty, the system then reads the data from the input device to the buffer.

    1) Read the file into memory:


    Connect BufferedInputStream with FileInputStream

    FileInputStream in= new FileInputStream( “file1.txt ” );

    BufferedInputStream bin=new BufferedInputStream( in);

    2) Write memory to file:

    Connect BufferedOutputStream with FileOutputStream

    FileOutputStreamout=new FileOutputStream(“file1.txt”);

    BufferedOutputStream bin=new BufferedInputStream(out);

    3) The keyboard input stream is read into the memory


    Connect BufferedReader with the standard data stream

    InputStreamReader sin=new InputStreamReader (System.in);

    BufferedReader bin=new BufferedReader(sin);

    #import java.io.*;


    #public

    class ReadWriteToFile {


    public

    static
      void main(String args[])
    1. throws IOException {

    2. # InputStreamReader sin =
      new InputStreamReader(System.in);

    3. ## BufferedReader bin = new BufferedReader(sin);

    4. FileWriter out =
    5. new FileWriter(

      "myfile.txt"); # BufferedWriter bout = new BufferedWriter( out);

    6. ## String s;
    7. while ((s = bin.readLine()).length( ) >

      0) {
    8. ##                   bout.write(s,

      0, s.length());
    9. # } }

    10. ## }

    11. }
    12. Program description:
      Read characters from the keyboard and write them to the file. Method of the BufferedReader class: String readLine()
      Function: Read a line of string, ending with a carriage return character.
      Methods of the BufferedWriter class: bout.write(String s,offset,len)
      Function: Start string s from offset in the buffer, and write a string of len length to a certain at.



      8. Character stream Writer/Reader

      Characters in Java adopt the Unicode standard. One character is 16 bits, that is, one character is represented by two bytes. To this end, streams for processing characters were introduced in JAVA.

      1. Reader abstract class

      An abstract class used to read character streams. The only methods that subclasses must implement are read(char[], int, int) and close(). However, most subclasses will override some of the methods defined here to provide greater efficiency and/or additional functionality.

                                                                                                                                                                                                                                      1) FileReader:

      Corresponds to FileInputStream :

        (1) Take the file name as a string: FileReader f=new FileReader(“c:/temp.txt”);   (2) The constructor takes the File object as its parameter.        File f=new file(“c:/temp.txt”);
             FileReader f1=new FileReader(f); fd=new FileDescriptor()
           FileReader f2=new FileReader(fd); Character array as input stream: CharArrayReader(char[], int, int)
      Read string, the constructor is as follows: public StringReader(String s);

      2) CharArrayReader:
      and ByteArrayInputStream Corresponds to
       
      3) StringReader:
      Corresponds to StringBufferInputStream  4) InputStreamReader

        Read bytes from the input stream and convert them into characters: Public inputstreamReader( inputstream is);
       5) FilterReader: Allows filtering of character streams
        protected filterReader(Reader r);  6) BufferReader:
      Accepts Reader objects as parameters, And add a character buffer to it, and use the readline() method to read a line. Public BufferReader(Reader r);
      Main method:
      (1) public int read() throws IOException; //Read a character, the return value is read The characters taken

       (2) public int read(char cbuf[]) throws IOException; /*Read a series of characters into the array cbuf[], and the return value is the actual read character Quantity*/  (3) public abstract int read(char cbuf[],int off,int len) throws IOException;
       /*Read len characters, starting from the subscript off of the array cbuf[] Storage, the return value is the actual number of characters read, this method must be implemented by a subclass*/

      2. Writer abstract class

      Abstract class for writing character streams. The only methods that subclasses must implement are write(char[], int, int), flush(), and close(). However, most subclasses will override some of the methods defined here to provide greater efficiency and/or additional functionality. Its subcategories are as follows:

      1) FileWrite: Corresponds to FileOutputStream
      Writes character type data to the file, using the default character encoding and buffer size.
       Public FileWrite(file f);
       2) chararrayWrite: Corresponds to ByteArrayOutputStream, using the character buffer as output.
        Public CharArrayWrite();
       3) PrintWrite: Generate formatted output
        Public PrintWriter(outputstream os);
       4) filterWriter: Used to write filter character stream
        protected FilterWriter(Writer w);
      5) PipedWriter: Corresponds to PipedOutputStream  

      6) StringWriter: There is no corresponding byte-oriented stream

      Main method:

       (1) public void write(int c) throws IOException; //Write the lower 16 bits of the integer value c to the output stream
       (2) public void write(char cbuf[]) throws IOException; //Write the character array cbuf[] to the output stream
       (3) public abstract void write(char cbuf[],int off,int len) throws IOException; //Write the characters in the character array cbuf[] IndexWrite len characters starting at the off position to the output stream
       (4) public void write(String str) throws IOException; //Write the characters in the string str to the output stream
       (5) public void write(String str,int off,int len) throws IOException; //Write len characters starting from index off in string str to the output stream
       (6) flush( ) //Flush the output stream and output all buffered bytes.
       (7)close() Close the stream public abstract void close() throws IOException

      3. Difference between InputStream and Reader Difference between OutputStream and Writer

      The InputStream and OutputStream classes process byte streams, and the smallest unit in the data stream is bytes (8 bits)
      Reader and Writer process characters Stream, when processing character streams, the problem of character encoding conversion is involved


      1. ##import java.io.* ;

      2. ##public

        class EncodeTest {

      3. ##private
      4. static

        void readBuff(byte [] buff) throws IOException { # ByteArrayInputStream in =

        new ByteArrayInputStream(buff);
      5. ##int data;

      6. ## while((data=in.read())!=-1) System.out.print(data+" ");

      7. System.out.println(); in.close(); }

      8. #public
      9. static

        void main(String args[])
        throws IOException {

      10. ## System.out.println ("Unicode character encoding is used in memory:");

      11. char c=
      12. 'Good';

      13.                  

        int  lowBit=c&0xFF;                                                                                                           ’               ’ dle dle dle dle it dle it it it it it t t t t t i ‐ i t o i s ,                                              

      14. System.out.println(""+lowBit+" "+highBit);

      15. String s="Good";

      16. ## System.out.println(

        "Local operating system default character encoding : ");

      17. readBuff(s.getBytes());

      18. System.out.println(

        " Using GBK character encoding: ");

      19. # readBuff(s.getBytes(
      20. "GBK"));

      21. System.out.println(
      22. "Using UTF-8 character encoding:");

        ## readBuff(s.getBytes(
      23. "UTF- 8")); }
      24. }


      ##Reader The class can convert characters in other encoding types in the input stream into Unicode characters, and then allocate memory for them in memory.

      Writer class can convert Unicode characters in memory into characters in other encoding types, and then write them to the output stream. middle.






      9. Subclass of IOException exception class


      1.public class EOFException:

      This type of exception is thrown when the end of the file or the end of the input stream is reached abnormally.

      2.public class FileNotFoundException:

      Exception thrown when the file cannot be found.

      3.public class InterruptedIOException:

      This type of exception is thrown when the I/O operation is interrupted.

    The above is the detailed content of Java input stream output stream. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn