Java input/output stream (1)

Source: Internet
Author: User

Java input/output stream (1)

1. What is IO?

In Java, I/O operations mainly refer to the use of Java for input and output operations. all Java I/O mechanisms are input and output based on data streams, which represent the flow sequence of character or byte data. Java I/O Stream provides a standard method for reading and writing data. Any object in Java that represents a data source can read and write data in the form of data streams.

Java. io is the main software package for most data stream-oriented input/output classes. In addition, Java also supports block transmission. Block IO is used in the core library java. nio.

The advantage of stream IO is that it is easy to use and its disadvantage is that it is less efficient. Block I/O efficiency is high, but programming is complicated.
Java IO model:
The I/O model of Java is well designed. It uses the Decorator mode and divides streams by function. You can dynamically assemble these streams to obtain the functions you need. For example, if you need a buffer file input stream, FileInputStream and BufferedInputStream should be used in combination.

2. Basic concepts of data stream

A Data Stream is a collection of continuous data. It is like a water flow in a water pipe. Water is supplied at 1.1 points at one end of the water pipe, what we see at the other end of the pipe is a continuous flow of water. A Data Writing program can write data into a Data Stream pipeline in a certain period of time. These data segments form a long data stream in sequence. For the data reading program, we can't see the segmentation of the data stream when writing. Each time we can read data of any length, we can only read the previous data before reading the subsequent data. No matter whether the data is written multiple times or as a whole, the reading effect is the same.

"A stream is the source or endpoint of data stored on a disk or other peripheral devices ."

There are three storage methods for data on the computer: External Storage, memory, and cache. For example, hard disks, disks, and USB flash drives on a computer are all stored externally. Memory is stored on the computer and cached on the CPU. External Storage has the largest storage capacity, followed by memory, and finally cache. However, external storage reads the slowest data, followed by memory, and the fastest cache. Here we will summarize how to read data from external memory to memory and write data from memory to external memory. For memory and external storage, we can simply understand it as a container, that is, external storage is a container, and memory is another container. Then, how can we read the data stored in the external storage container to the memory container and how can we store the data in the memory container to the external storage?

In Java class libraries, I/O content is very large, because it involves a wide range of fields:

Standard input and output, file operations, data streams on the network, string streams, object streams, zip file streams, etc,In java, input and output are abstracted as streams.It is like a pipe that connects two containers. The input stream is used to read data from the external store to the memory, and the output stream is used to write data from the memory to the external store.

Stream is a very visual concept. When the program needs to read data, it will open a stream to the data source, which 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 are summarized as follows:

1) Data Stream:

A group of ordered data sequences of bytes with the starting and ending points. Including the input stream and output stream.

2) Input Stream ):

The program reads the data source from the input stream. Data sources include external sources (keyboards, files, networks, etc ...), That is, the communication channel that reads the data source into the program


3) output stream: The program writes data to the output stream. Output Data in the program to the outside world (display, printer, file, network ...) .

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

Input Stream does not care about the device (keyboard, file, network) from which the data source comes)
Output Stream does not care which device (keyboard, file, network) the data is)

4. data stream classification: data in a stream sequence can be either raw binary data that has not been processed, or specific data that has been encoded to conform to certain formats. Therefore, Java streams are divided into two types:
1) byte stream:The smallest data unit in a data stream is byte.
2) streams:The smallest data unit in a data stream is a character. The 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. It also specifies the way to exchange information with standard input and output devices, such as keyboards and monitors. Files can exchange information in any form 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 ++ ){
  4. System. out. println ("args [" + I + "] is <" + args [I] + "> ");
  5. }
  6. }
  7. }

    Run the following command: java Java C VB

    Running result:

    Args [0] is

    Args [1] is

    Args [2] is

    2. Standard input and output data streams

    Java. lang. System:

    1. Java. lang. System
    2. Public final class System extends Object {
    3. Static PrintStream err; // standard error stream (output)
    4. Static InputStream in; // standard input (keyboard input stream)
    5. Static PrintStream out; // standard output stream (Display output stream)
    6. }

      Note:
      (1) The System class cannot create objects. It can only use three static members of the System class.
      (2) Each time 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 deviceThe data type is PrintStream. Method:

      Void print (parameter) Void println (parameter)

      2) standard input stream System. in

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

      Int read () // returns the ASCII code. If the returned value is-1, it indicates that no Bytes have been read. Int read (byte [] B) // read multiple bytes to buffer B. The returned 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. Int B;
      5. Try {
      6. System. out. println ("please Input :");
      7. While (B = System. in. read ())! =-1 ){
      8. System. out. print (char) B );
      9. }
      10. } Catch (IOException e ){
      11. System. out. println (e. toString ());
      12. }
      13. }
      14. } Wait for the keyboard input, and print the keyboard input:

        3) standard error stream

        System. err output standard errorThe data type is PrintStream. See the API for details.

        The standard output calls the println method through System. out to output parameters and wrap them. The print method outputs parameters but does not wrap them. Both println and print methods have implemented multiple methods for outputting basic data types through overload, including the output parameter types: boolean, char, int, long, float, and double. At the same time, the output parameters of char [], String, and Object types are also overloaded. The print (Object) and println (Object) Methods call the toString method of the parameter Object at runtime.

        1. Import java. io. BufferedReader;
        2. Import java. io. IOException;
        3. Import java. io. InputStreamReader;
        4. Public class StandardInputOutput {
        5. Public static void main (String args []) {
        6. String s;
        7. // Create a buffer reader to read data row by row from the keyboard
        8. InputStreamReader ir = new InputStreamReader (System. in );
        9. BufferedReader in = new BufferedReader (ir );
        10. System. out. println ("Unix System: ctrl-d or ctrl-c Exit"
        11. + "\ NWindows: ctrl-z exit ");
        12. Try {
        13. // Read a row of data and output it to the display.
        14. S = in. readLine ();
        15. // If an I/O error occurs during the readLine () method running, an IOException is thrown.
        16. While (s! = Null ){
        17. System. out. println ("Read:" + s );
        18. S = in. readLine ();
        19. }
        20. // Close the buffer Reader
        21. In. close ();
        22. } Catch (IOException e) {// Catch any IO exceptions.
        23. E. printStackTrace ();
        24. }
        25. }
        26. }

          4. java. IO layered architecture

          Five classes and one interface are the most important in the entire Java. io package. Five classes refer to File, OutputStream, InputStream, Writer, and Reader. One interface refers to Serializable. after mastering these core IO operations, I have a preliminary understanding of the IO System in Java.

          Java I/O consists of the following layers:

          1. Stream part-Main part of IO;

          2. Non-streaming part-It mainly contains classes of the secondary stream, such as File, RandomAccessFile, and FileDescriptor;

          3. Other classes-- Security-related classes for file reading, such as SerializablePermission and file system classes related to local operating systems, such as FileSystem, Win32FileSystem, and WinNTFileSystem.

          The main classes are as follows:

          1. File (File features and management): used for describing a File or directory, such as generating a new directory, modifying the File name, deleting the File, and determining the path of the File.

          2. InputStream (binary format operation): abstract class, byte-based input operation, is the parent class of all input streams. Defines the common features of all input streams.

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

          In Java, the character adopts the Unicode standard. A character is a 16-bit character, that is, a character is expressed in two bytes. To this end, JAVA introduces Stream processing characters.

          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,Attackers can access (input and output) files from any location..

          Architecture of IO stream in Java


          <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KCjxoMj4KPHAgY2xhc3M9 "headline-1 bk-sidecatalog-title"> 5. Non-streaming File class-File class


          In the Java. io package of java, the File class provides operations and management methods to describe 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 and is used to manage disk files and directories.

          Role: The File class is mainly used to name files, query File attributes, and process File directories.
          1. Public class File extends Object
          2. Implements Serializable, Comparable
          3. {}

            The File class provides three different constructors to flexibly receive File and directory name information with different parameters. Constructor:
            1) File (String pathname)For example, File f1 = new File ("FileTest1.txt"); // create a File object f1,f1the File specified is the File test1.txt created under the current directory.
            2) File (String parent, String child)For example, File f2 = new File ("D: \ dir1", "FileTest2.txt"); // Note: The D: \ dir1 directory must exist in advance; otherwise, an exception occurs.
            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 () create a File object corresponding to a disk File or directory. Once it is created, you can call it to obtain the attributes of the File or directory. 1) public boolean exists () to determine whether a file or directory exists
            2) public boolean isFile () determines whether it is a file or a directory.
            3) public boolean isDirectory () determines whether it is a file or a 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 object length
            7) public String [] list () stores all file names in the directory in the String array and returns the results. The File class also defines some methods for managing and operating files or directories. Common methods include:
            1) public boolean renameTo (File newFile); rename the File
            2) public void delete (); delete an object
            3) public boolean mkdir (); create a 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 = new File ("\ root ");
            6. File f1 = new File (dir, "fileOne.txt ");
            7. File f2 = new File (dir, "fileTwo. java ");
            8. // After a file object is created, the specified file or directory may not exist physically.
            9. If (! Dir. exists ())
            10. Dir. mkdir ();
            11. If (! F1.exists ())
            12. F1.createNewFile ();
            13. If (! F2.exists ())
            14. F2.createNewFile ();
            15. System. out. println ("f1's AbsolutePath =" + f1.getAbsolutePath ());
            16. System. out. println ("f1 Canread =" + f1.canRead ());
            17. System. out. println ("f1's len =" + f1.length ());
            18. String [] FL;
            19. Int count = 0;
            20. FL = dir. list ();
            21. For (int I = 0; I <FL. length; I ++ ){
            22. Count ++;
            23. System. out. println (FL [I] + "is in \ root ");
            24. }
            25. System. out. println ("there are" + count + "file in // root ");
            26. }
            27. }

              Note: Methods of the File class:
              (1) exists () test whether the specified file or directory on the disk exists
              (2) mkdir () Create the directory specified by the file object (single-layer directory)
              (3) createNewFile () Create the file specified by the file object

              (4) list () returns all file name strings in the directory

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.