Java Learning Note-The tenth chapter data input and output

Source: Internet
Author: User
Tags create directory

The tenth chapter data input and output

  1. Input stream and output stream:

    (1) input stream: The flow of input data into the program is defined as the input stream, based on the program's baseline. The input data from the input flow program is called read data.

    (2) output stream: A program-based flow of output data from a program is called an output stream. outputting data from the program to the output stream is called write data.

    650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/6B/E6/wKioL1U559bDrdRTAABay7cxCgk667.jpg "title=" Untitled. png "alt=" wkiol1u559bdrdrtaabay7cxcgk667.jpg "/>

    650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/6B/EA/wKiom1U55vLz4eWbAABaWeLqq4s763.jpg "title=" Untitled. png "alt=" wkiom1u55vlz4ewbaabawelqq4s763.jpg "/>

  2. Byte Stream and character stream

    (1) byte stream: Reads/writes data in bytes. Abstract classes InputStream and OutputStream in Java and their derived subclasses are used to handle the input and output of a byte stream.

    (2) Character stream: Reads/writes data in the form of characters. Abstract class reader and writer and their derived subclasses in Java are used to handle the input and output of a character stream.

    (3) the system provides systems classes for standard input, output, and scanner classes for parsing various types of data such as integers, floating-point numbers, strings, and so on.

    (4) Although Java is essentially dividing the input/output stream into a byte stream and a character stream, it does not mean that the input/output data can only be processed in the form of these two lowest levels. In fact, you can also enter/output various types of data by invoking the constructor and member methods of many classes.

  3. Byte and character input/output stream classes

    (1) byte input stream class InputStream: used to read data from the data source in bytes. It is the parent class of all byte input stream classes. is an abstract class and cannot be instantiated. The main derived subclasses are: FileInputStream (reading data from a file in bytes), Bufferedinputstream (saving data read as bytes into a buffer), and so on. The hierarchy is as follows:

    InputStream

    Bytearrayinputstream

    FileInputStream

    FilterInputStream

    Bufferedinputstream

    DataInputStream

    Linenumberinputstream

    Pushbackinputstream

    ObjectInputStream

    PipedInputStream

    Sequenceinputstream

    StringBufferInputStream

    Among them, Bufferedinputstream is a very useful class, it can buffer the input data, so as to improve the data input efficiency. It is constructed by: public Bufferedinputstream (InputStream in). Where in can be either a file input stream or a keyboard input stream. Several of the main methods of this class are:

    A. public void Close (): closes this input stream and frees all system resources associated with the stream.

    B. public abstract int Read (): reads the next byte of data from the input stream. The return value is an integer that returns 1 if the end of the stream is reached.

    c. public int read (byte[] b): the content read from the input stream is stored in byte array B. The return value is the number of bytes read in. Returns 1 if no more data is available at the end of the stream.

    Note: When you enter data from the keyboard (that is, the data source is system.in), the Read () method is blocked until you press ENTER. If you press the "CTRL + Z" key to indicate the end of the input stream, the contents of the row input are ignored, and the read () return value is-1. When the file is read (the data source is a FileInputStream class object), the Read () method returns a value of-1 if the end of the file is reached.

    (2) byte output stream class OutputStream: used to write data to a destination in bytes. The main derived subclasses include: FileOutputStream (writes data to a file), PrintStream (for outputting various types of data, such as integers, floating-point numbers, characters, strings, booleans, etc., the main methods are print () and println ()), and so on. The hierarchy is as follows:

    OutputStream

    Bytearrayoutputstream

    FileOutputStream

    Filteroutputstream

    Bufferedoutputstream

    DataOutputStream

    PrintStream

    ObjectOutputStream

    PipedOutputStream

    The Bufferedoutputstream class can buffer the output data and improve the data output efficiency. This class is constructed as follows:

    Public Bufferedoutputstream (OutputStream out)

    Represents the creation of a new buffered output stream to write data to the specified underlying output stream.

    A. public void Close (): closes this buffered output stream and frees all system resources related to this stream.

    b. public void write (int b): writes the specified bytes to this buffered output stream.

    c. public void Write (byte[] b): writes B.length bytes to this buffered output stream.

    (3) character input stream class reader: reads data from the data source as characters. The main derived subclasses include: InputStreamReader (reading byte data and decoding it to characters), FileReader (reading the contents of the character file), BufferedReader (reading the text from the character input stream, buffering individual characters, thus implementing characters, Efficient reading of arrays and rows). The hierarchy is as follows:

    Reader

    BufferedReader

    LineNumberReader

    CharArrayReader

    FilterReader

    Pushbackreader

    InputStreamReader

    FileReader

    Pipedreader

    StringReader

    Among them, the InputStreamReader class is constructed by: public InputStreamReader (InputStream in);

    The main member methods are:

    A. public void Close (): closes the stream and frees all resources associated with it.

    B. public int read (): reads a single character.

    c. public int read (char[] c): reads the characters into the array. The return value is the number of characters read. Returns 1 if the end is reached.

    The BufferedReader class is constructed as public BufferedReader (Reader in), which is used to create a buffered character input stream that uses the default size input buffer. Its member method is similar to InputStreamReader, except for a new ReadLine () method, which is declared in the following way and function:

    Public String ReadLine (): reads a line of text. A line is considered terminated by one of the following characters: line break (' \ n '), carriage return (' \ R '), or carriage return followed by line wrapping. Its return value is a string containing the contents of the row, and does not contain any line terminators. If the end of the stream has been reached, NULL is returned.

    (4) character output stream class Writer: writes data to the destination in the form of a character. The writer class is the parent class of all character output stream classes, and its main derived subclasses are: OutputStreamWriter (writes characters in bytes to the output stream), FileWriter (writes character data to a file), BufferedWriter (writes character data to buffer), PrintWriter (formatted output character data), and so on. The hierarchy is as follows:

    Writer

    BufferedWriter

    Chararraywriter

    Filterwriter

    OutputStreamWriter

    FileWriter

    PipedWriter

    PrintWriter

    StringWriter

    Among them, the OutputStreamWriter class is constructed by: public OutputStreamWriter (OutputStream out);

    Its main member methods include:

    A. public void Close (): closes this stream.

    b. public void write (int c): writes a single character.

    c. public void Write (char[] c): writes a character array.

    d. public void Write (String str): writes a string.

    The BufferedWriter class is constructed as public bufferedwriter (Writer out), and its main member methods are:

    A. public void close (); Closes the stream.

    b. public void write (int c); Writes a single character.

    c. public void Write (char[] c); Writes an array of characters.

    d. public void write (String str); Writes a string.

    E. public void NewLine (); Writes a line delimiter.

  4. Using the scanner class to enter data of various types

    The scanner class is a simple text scanner that can use regular expressions to parse basic types and strings. The important methods of this class are as follows:

    (1) Nextbyte (), Nextshort (), Nextint (), Nextlong (), Nextfloat (), nextdouble (), Nextboolean () are respectively used to read bytes, short integer, Integer, Long Integer, Floating-point numbers, double-precision floating-point numbers, and Boolean values.

    (2) Hasnextbyte (), Hasnextshort (), Hasnextint (), Hasnextlong (), Hasnextfloat (), hasnextdouble (), Hasnextboolean () The method is used to determine if the data to be read is a byte, a short integer, an integer, a long integer, a floating-point number, a double-precision floating point, or a Boolean value.

    (3) The Nextline () method is used to read a row of data, and if the data is read using Nextbyte (), Nextshort (), this method is used to read subsequent data in the current row, and the Hasnextline () method is used to confirm that there is another row of data. This method is primarily for files and is used to determine if the end of the file is reached.

    If you enter multiple data in a row, you can split the data with a space.

  5. Master the methods of writing and reading and managing documents

    (1) File byte input/output streams: Refers to the FileInputStream and FileOutputStream classes, which implement sequential access to files and read/write operations in bytes. In Java, the main steps to read/write to a file are: ①. Create a file input/output stream object, at which time the file is automatically opened or created; ②. Read and write data using a file read/write method; ③. Closes the data stream and closes the file.

    A. FileInputStream class: construction method is as follows:

    FileInputStream (String name)

    FileInputStream (File file)

    Where name indicates the name of the file to open, and file represents the object of the files class. For example:

    Create a file input stream object while opening a file

    FileInputStream fis = new FileInputStream ("D:\\test.txt");

    If you do not find the file you want to open, the system throws an FileNotFoundException exception.

    B. FileOutputStream class: writes data to a file, constructed as follows:

    FileOutputStream (String name)

    FileOutputStream (String Name,boolean append)

    FileOutputStream (File file)

    Where, in the FileOutputStream (string name) construction method, name represents the file name to be created and opened, and in the FileOutputStream (string Name,boolean Append) constructor method, When the value of the parameter append is true, the data is added at the end of the original file, otherwise the contents of the original file are overwritten, and in the FileOutputStream (file file) Construction method, file represents the FileName object. For example:

    Create a file class object file

    File File = new file ("D:\\test.txt");

    Creating a file output stream class object based on the files class object file Fos, new D:\\test.txt Object

    FileOutputStream fos = new FileOutputStream (file);

    Note: The FileInputStream class and the FileOutputStream class inherit the Read () method and the Write () method of the InputStream and OutputStream classes so that the open file can be read/write. The input/output stream program throws a non-runtime exception ioexception, so it must be thrown at the declaration of the method or captured using the Try-catch statement. To avoid wasting system resources, when you no longer use the stream, you need to close the stream using the close () method, which is actually closing the file.

    (2) file character input/output stream

filereader (file file)

FileReader (String filename)

FileWriter (String finename)

FileWriter (String Filename,boolean append)

FileWriter (File file)

FileWriter (File File,boolean append)

Where file is the object of the files class, filename is the name to open, and when the parameter append value is True, the data is added at the end of the original file, otherwise the contents of the original file will be overwritten.

(3) using file class to manage files

In Java, the file class can represent both files and directories, and it provides a set of methods for manipulating files or directories.

A. Construction method;

File (String pathname): Creates a new file instance by converting the given path string to an abstract path name.

File (String parent,string Child): creates a new File instance based on the parent pathname string and the children pathname string.

file parent,string Child: Creates a new File instance based on the parent abstract path name and children pathname string.

Note: Abstract pathname is actually a string, which begins with "drive letter:" followed by "\ \ Pathname or filename", where the middle name represents the directory, and the last name can represent a directory or a file. In addition, the path part of the abstract path is referred to as the parent directory. Because "\ \" is an escape character, "\ \" actually means "\".

B. Querying the file name and path name

Public String GetName (): Returns the name of the file or directory represented by this abstract path name.

Public string GetPath (): converts this abstract pathname to a path name string.

Public string GetAbsolutePath (): returns the absolute path name string for this abstract pathname.

Public string GetParent (): returns the path string of the parent directory for this abstract path name. If the path name does not specify a parent directory, NULL is returned.

c. Abstract path Query

Public Boolean exists (): tests whether the file or directory represented by this abstract path name exists. Returns true if it exists, or false if it is present.

Public Boolean isdirectory (): tests whether this abstract path name represents a directory. If true, returns false otherwise.

Public Boolean isfile (): tests whether this abstract path name represents a standard file. If true, returns false otherwise.

Public Boolean Ishidden (): tests whether this abstract path name represents a hidden file. If true, returns false otherwise.

D. File and directory operations

Public Boolean CreateNewFile (): creates a new empty file when and only if the file specified by this abstract pathname does not exist. Returns true if the specified file does not exist and is created successfully;

Public Boolean mkdir (): creates the directory specified by this abstract path name. Returns true if the creation was successful, otherwise false. If the path name has multiple layers, you must ensure that the previous path is valid. For example, the content of the Jiading file object is "C:\\abc\\xyz", then to call the MkDir () method to create the XYZ directory, you must first ensure that the "C:\ABC" directory exists. This is the only way to create directory XYZ under the "C:\ABC" directory.

Public Boolean Delete (): deletes the file or directory represented by this abstract path name. If this abstract path name represents a directory, the directory must be empty to be deleted. Returns true if and only if the file or directory has been successfully deleted, otherwise false.

Public string[] List (): lists the files and directories in the directory represented by this abstract path name. If this abstract name represents a directory other than the one, this method returns NULL, otherwise an array of strings, each of which corresponds to a file or directory in the directory, is returned.

(4) Use the Randomaccessfile class to read and write files randomly

byte input/output streams and character input/output streams are sequential read/write files, while the Randomaccessfile class provides a way to randomly access files. The Randomaccessfile class has two different points from the input/output stream class:

A. The Randomaccessfile class inherits the object class directly, implements both the Datainput interface and the DataOutput interface, so the Randomaccessfile class can be either an input stream or an output stream.

B. The Randomaccessfile class defines a pointer to the current location of a file, and the file is read from the location indicated by the current position of the file. By moving this pointer, you can start a read/write operation from anywhere in the file. At the same time, when the system reads data from a file or writes data to a file, the position pointer moves automatically.

C. Construction method

randomaccessfile (File file,string mode)

Randomaccessfile (String name,string mode)

Where file is a document object; mode is the access mode with three values: R (Read), W (write), rw (read-write). For example, the following statement creates a random Access file Object Rd, the file name is A.txt, and the file property is read-only.

Randomaccessfile rd = new Randomaccessfile ("A.txt", r);

D. Common methods

Public Long Getfilepointer (): returns the position of the file pointer;

Public long Length (): Returns the length of the file;

Public void Seek (Long pos): moves the file pointer to the POS location;

public int skipbytes (int n): causes the file pointer to skip n bytes;

Public Void Close (): closes this random access file stream and frees all system resources associated with the stream;

public int Read (): reads a data byte from this file. Returns this byte as an integer, returning from 0 to 255;

public int Read (byte[] b): reads a maximum of b.length data bytes from this file into a byte array;

Public final Char ReadChar (): reads a character (two bytes) from the current pointer of the file;

Public final Double readdouble (): reads a double data (8 bytes) from the current pointer of the file;

Public final Float readfloat (): reads a float data (4 bytes) from the current pointer of the file;

Public final int readInt (): reads a signed 32-bit integer (4) byte from the current pointer of the file. Similarly, the system provides the Readlong () method (8 bytes), the Readshort () method (2 bytes), and so on;

Public void Write (int b): writes the specified byte to the file, starting at the current pointer position of the file;

Public void Write (int[] b): writes B.length bytes from the specified byte array to the file starting at the current file pointer position;



Java Learning Note-The tenth chapter data input and output

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.