Java Fundamentals (11) Stream I/O and Files

Source: Internet
Author: User

Java Foundation (11) Stream I/O and Files1. The concept of flow

The main task of the program is to manipulate the data. In Java, a set of ordered sequences of data is called a stream. Depending on the direction of the operation, the flow can be divided into two types of input and output streams. The program reads the data from the input stream and writes out the data to the output stream.

     文件    输入流                     输出流           文件     内存 ------------->  Java程序 ------------------>  内存     键盘                                              控制台      |                                                  |    数据源                                            数据目的地

The Java I/O system is responsible for processing the input and output of the program, the I/O class library is located in the Java.io package, which abstracts the various common input and output streams.

If the smallest unit of data in the data stream is a byte, then the stream is called a word stream, and if the smallest unit of data in the stream is a character, it is called a stream of characters.

    • In the I/O class library, Java.io.InputStream and java.io.OutputStream represent byte input streams and byte output streams respectively;
    • Java.io.Reader and Java.io.Writer represent character input streams and character output streams, respectively.
    • Note: All four of them are abstract (reader/writer/inputstream/outstream)
2. Byte input stream and output stream

In the Java.io package, Java.io.InputStream represents the byte input stream, Java.io.OutputStream represents the byte output stream, which are abstract classes and cannot be instantiated.

The InputStream class provides a series of methods for reading data:

  • Read (): reads data from the input stream: There are three overloaded forms:

    • int read (): reads a 8-bit byte from the input stream (1 bytes is 8 bits), converts it to an integer between 0-255, and returns this integer. Returns 1 if the end of the input stream is encountered;
    • int read (byte[] b): reads several bytes from the input stream and saves them to the byte array specified in Parameter B. The returned integer represents the number of bytes read. Returns 1 if the end of the input stream is encountered;
    • int read (byte[] b, int off, int len): reads several bytes from the input stream and saves them to the byte array specified in Parameter B. The returned integer represents the number of bytes read. The off parameter specifies the starting subscript to start saving data in the byte array, and the parameter Len specifies the number of bytes to read. The returned integer represents the number of bytes that the implementation reads. Returns 1 if the end of the input stream is encountered;

    The first read method reads one byte from the input stream, while the remaining two read methods bulk reads a number of bytes from the input stream. When reading data from a file or keyboard, the following two read methods can reduce the number of physical read files or keyboards, thereby improving the efficiency of I/O operations.

  • void Close (): Closes the input stream, and the close () method of the InputStream class itself performs no action. Some of its subclasses override the close () method, freeing and streaming system resources in the close () method.

  • int available (): Returns the number of bytes that can be read from the input stream;
  • Skip (Long): Skips the parameter n specified number of bytes from the input stream.
  • Boolean marksupported (), void mark (int), void Reset (): If you want to read the data repeatedly from the stream,
    • The marksupported () method is used to determine whether this stream supports repeated read-in data, and if true, indicates that the token can be set on the stream.
    • Next, the mark (int readlimit) method is called to set the tag starting at the current position of the stream.
    • Finally, call the Reset () method, which repositions the input stream to the starting position where the marker was just made. This makes it possible to read the tagged data repeatedly.

The Ouputstream class provides a series of methods for writing data:

    • Write (): writes data to the output stream: There are three overloaded forms:

      • void write (int b): Writes a byte to the output stream;
      • void Write (byte[] b): Writes all bytes in the byte array specified by parameter B to the output stream;
      • void Write (byte[] b, int off, int len): Writes all the bytes in the byte array specified by parameter B to the output stream, the parameter off specifies the starting subscript for the byte array, starting from this position outputs the specified number of bytes by the parameter Len;

      The first write method above writes one byte from the output stream, while the remaining two write methods write out several bytes in bulk from the output stream. When writing data to a file or console, the following two write methods can reduce the number of physical reads of a file or keyboard, thereby increasing the efficiency of I/O operations.

    • void Close (): Closes the output stream, and the close () method of the OutputStream class itself performs no action. Some of its subclasses override the close () method, freeing and streaming system resources in the close () method.

    • void Flush (): The Flush () method of the OutputStream class itself does nothing, and some of its subclasses with buffers (such as the Bufferedoutputstream and PrintStream classes) overwrite the flush () method. When writing data through the output stream with buffers, the data is stored in the buffer and accumulated to a certain extent before it is actually written to the output stream. Buffers are typically implemented in byte arrays, which in effect refer to a piece of memory space. The flush () method forces the data in the buffer to be written to the output stream.

3. Commonly used byte input stream and output stream
    • In: Input stream

      • Bytearrayinputstream: Reading data from an array of type Byte
      • FileInputStream: Reading data from a file;
      • PipedInputStream: (pipe flow) connecting a pipedoutputstream;
      • ObjectInputStream: Object input stream;
      • StringBufferInputStream: Can read a string that is obsolete in the API
    • Out: Output stream

      • Bytearrayoutputstream:
      • FileOutputStream
      • PipedOutputStream:
      • ObjectOutputStream
4. Bufferedinputstream class

The Bufferedinputstream class covers the read data behavior of the filtered input stream and uses buffers to improve the efficiency of the read data. The Bufferedinputstream class first reads a batch of data into the buffer, and then the read () method only needs to get the data from the buffer to reduce the number of physical read data.

    • Bufferedinputstream (InputStream in)--parameter in specifies the input stream that needs to be filtered.
    • Bufferedinputstream (inputstream in, int size)--parameter in specifies the input stream that needs to be filtered. Parameter size specifies the size of the buffer, in bytes.
5. DataInputStream class

DataInputStream implements the Datainput interface for reading basic types of data, such as int, float, long, double, and Boolean.

    • ReadByte ()--Reads 1 bytes from the input stream, referring to the data it converts to byte type;
    • Readlong ()--Reads 8 bytes from the input stream, which is converted to a long type of data;
    • Readfloat ()--reads 4 bytes from the input stream, referring to the data it converts to float type;
    • readUTF ()-Reads from 1 to 3 bytes from the input stream, referring to the string that it converts to the UTF-8 character encoding;
6. Pipeline Input class: PipedInputStream class

The pipeline stream reads data from a management output flow. Typically one thread writes data to the management output stream, and another thread reads data from the management input stream, and two threads can communicate with the pipeline.

7. Reader and writer Overview

The InputStream and OutputStream classes handle byte streams, which means that the smallest unit in the data flow is a byte, which includes 8 bits. In many applications, Java applications need to read and write text files. Characters encoded with a specific character are stored in a text file. To facilitate reading of characters encoded in various characters, the Reader/writer class is provided in the Java.io package, which represents the character input stream and the character output stream, respectively.

The main problem when dealing with character streams is the conversion of characters. The Java language is encoded with Unicode characters. For each character, a Java virtual opportunity allocates two bytes of memory for it. In text files, it is possible for characters to use other types of encoding, such as GBK and UTF-8 character encodings.

Reader classes can convert characters in the input stream that use other encoding types to Unicode characters, and then allocate memory for these Unicode characters in memory. The writer class is able to convert in-memory Unicode characters to characters of other encoded types, and then write to the output stream.

By default, reader and writer encode and convert between the character encoding of the local platform and the Unicode character encoding.

                        Writer的write()方法使用Unicode字符编码的字       ------------>   使用本地平台的字符编码的字符串符串(内存中)                 <------------   (数据源/数据目的地)                                       Reader的read()方法

If you want to enter or output a string with a specific type encoding, you can use the InputStreamReader class and the OutputStreamWriter class. In their construction methods, you can specify the character encoding of the input stream or output stream.

                    OutputStreamWriter的write()方法使用Unicode字符编码的字      --------------->   使用本地平台的字符编码的字符串符串(内存中)                 <--------------    (数据源/数据目的地)                                   InputStreamReader的read()方法

Because of the character encoding conversion technology used by reader and writer, the Java I/O system can correctly access text files with various character encodings, and on the other hand, when allocating memory for characters, the virtual machine Unicode character encoding is used uniformly. Therefore, Java program Processing characters have platform independence.

    • CharArrayReader: Converts a character array to reader and reads characters from a character array;
    • BufferedReader: A filter that provides read buffers for other readers, in addition, its readline () method is capable of reading into a line of strings;
    • StringReader: Converts a string to reader and reads characters from a string;
    • Pipedreader: Connecting a pipedwriter;
    • Pushbackreader: The read character can be pressed back into the buffer, usually used as a compiler scanner, in the program is generally very little use of it.
    • InputStreamReader: Filter, convert InputStream to reader, you can specify character encoding;
    • FileReader: Reading characters from a file;
8. InputStreamReader Class

The InputStreamReader class converts the InputStream type to reader type by constructing the method:

    • InputStreamReader (InputStream in): reads characters from the input stream according to the character encoding of the local platform;
    • InputStreamReader (InputStream in, String charsetname): reads the characters in the input stream according to the specified character encoding;
9. FileReader Class

A subclass of InputStreamReader that is used to read character data from a file. The class can only read data according to the character encoding of the local platform, and the user cannot specify other character encoding types.

    • FileReader (File file): A parameter that specifies files that need to be read;
    • FileReader (String name): The parameter name specifies the path of the file that needs to be read;
BufferedReader class
    1. The read () method of the reader class reads a character from the data source each time, bufferedreader with a buffer, which can read a batch of data into the buffer first.
    2. The next operation takes the data from the buffer and avoids reading the data from the data source and converting the character encoding each time, thus improving the efficiency of the read operation.

      • The BufferedReader ReadLine () method can read one line of characters at a time, returning as characters.
      • BufferedReader (Reader in): Specifies the modified Reader class;
      • BufferedReader (reader in, int sz): parameter in specifies the decorated Reader class, and the parameter sz specifies the size of the buffer, in characters.
One. File class

The file class provides methods for managing files or directories. A file instance represents a document or directory in the real file system.

  1. Construction method

    • File (String pathname): The parameter pathname indicates the path of the files or directory;
    • File (string parent, String child): The parameter parent represents the root path, and the parameter children represents a subpath;
    • File (file parent, String Child): The parameter parent represents the root path, and the parameter children represents a subpath;

    Working with only one file, using the first construction method, or, for example, working with several subdirectories or files of a common directory, it is more convenient to use a second or a third.

  2. Normal method

    • boolean createnewfile (): Creates a new file and if the file already exists, the creation fails (returns false) or the creation succeeds (returns True).
    • Boolean Delete (): Delete file or empty directory
    • boolean mkdir ()/mkdirs (): Create one or more directories (continuous creation), if the parent directory of the directory does not exist, All parent directories are also created;
    • boolean renameto (File destination): Renaming of Files
    • boolean canRead ()/canwrite () : Determines whether the specified file can read or write to Data
    • Boolean exists (): Determines whether the specified file or directory exists
    • string[] List (): Returns a string array of all file names or subdirectory names in the specified directory
    • Long LastModified (): Returns the time that the specified file was last modified (from January 1, 1970 12 o'clock in the morning to the number of milliseconds elapsed between the time the file was modified)
    • String GetPath ()/ GetAbsolutePath (): Returns the path and absolute path of the specified file or directory
    • string Getcanonicalpath (): Gets the normal path of the file or directory represented by this file object
    • string GetParent ()/getname (): Returns the parent directory of the specified file or directory (no null returned) and the first name
 file F = new File ()  System.out  .println  (F.getcanonicalpath  ())  system.out   (F.getabsolutepath  ())  system.out   . println  (F.getpath  ())  if (!f.exists  ()) F ()) ; 
FileInputStream and FileOutputStream
    • When creating a FileInputStream object, the file must be present and readable
      • FileInputStream (File file)
      • FileInputStream (String name)
    • When creating a FileOutputStream object, you can either create a new file or overwrite a file that already exists with the same name.
      • FileOutputStream (File file)
      • FileOutputStream (File File, Boolean append)

If the file you want to create already exists, you can choose to add new content to the old file (append is true) or overwrite the contents of the old file with the new content (append is false).

Note: Write a com.briup.ch14.CopyTime.java here

FileReader and FileWriter
    • Easy to read and write character files
    • Constructors
      • FileReader (File file)
      • FileReader (String name)
      • FileWriter (File file)
      • FileWriter (String filename)
FileReader:new FileReader(“d:/back/string.txt”) =    new InputStreamReader(new FileInputStream(“d:/back/string.txt”));FileWriter:new FileWriter(“d:/back/string.txt”) =    new InputStreamWriter(new FileOutputStream(“d:/back/string.txt”));
PrintWriter.

You can output basic data types, objects, characters (character arrays), and strings, but you cannot output a byte stream.

    • PrintWriter classes can replace bridges and BufferedWriter
    • The PrintStream class can output either a byte stream or a character stream or a string
Reading and Writing with Randomaccessfile
    • Implementation of data input and output
    • It provides the ability to read and write files.
    • Provides the ability to read and write data from a breakpoint on a file using a file pointer
    • Constructors
      • Randomaccessfile (file file, String mode)
      • Randomaccessfile (string filename, string mode)
      • Mode can choose how to read, write and read and write
    • Method:
      • Read ()/write ()
      • Seek (long pointer) to locate a breakpoint on a file
16. Serialization and deserialization of objects

Serialization of objects: Writes an object to an output stream;
Deserialization of an object: Reading an object from an input stream;

Points:

    • Persistence of objects
    • Only the data of an object is serialized (serializes the object's data into a byte stream)
    • Data that is identified as transit cannot be serialized for example: transit 类名 indicates that the class cannot be serialized ortransit 字段
    • The object to serialize must implement the Java.io.Serializable interface

The serialization of objects is primarily used to:

    • The transmission of the data in the network is the byte stream, and the transmission of the object in the network is the conversion of the object's data into a byte stream.
    • Serializes the object data into a file, converting the object data into a byte stream to be stored in a file.
    • Converting an object to a byte stream is called the serialization of an object, and converting a byte stream to an object is called deserialization of an object.

ObjectInputStream and ObjectOutputStream (object input and output streams, basic data types and objects can be read and written)

    • ObjectInputStream and ObjectOutputStream persist storage for applications that provide objects
    • A objectinputstream can deserialize basic data types and objects written by ObjectOutputStream
    • Constructors
      • ObjectInputStream (InputStream in)
      • ObjectOutputStream (OutputStream out)
    • Method
      • ReadObject ()/writeobject () writes an object to the output stream or reads an object from the input stream

Java Fundamentals (11) Stream I/O and Files

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.